package com.feib.soeasy.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.PrintSetup;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedCaseInsensitiveMap;

import com.feib.soeasy.dao.CodeTableDao;
import com.feib.soeasy.dao.CommissionCodeTableDao;
import com.feib.soeasy.dao.GroupDao;
import com.feib.soeasy.dao.PaymentDao;
import com.feib.soeasy.dao.RealAccountDao;
import com.feib.soeasy.dao.Soez5008Dao;
import com.feib.soeasy.model.CommissionCodeTable;
import com.feib.soeasy.model.Group;
import com.feib.soeasy.model.Payment;
import com.feib.soeasy.model.RealAccount;
import com.feib.soeasy.model.WriteOffPayment;
import com.feib.soeasy.pagination.PaginatedList;
import com.feib.soeasy.service.Soez5008Service;
import com.feib.soeasy.util.DateUtil;
import com.feib.soeasy.util.SoezListBean;
import com.feib.soeasy.util.UserUtil;


/**
 * @title (#)Soez5008ServiceImpl.java<br>
 * @description <br>
 * @author Jimmy Liu<br>
 * @version 1.0.0 2010/11/25
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @2011/3/14 create by Jimmy Liu<br>
 */
@Service("soez5008Service")
public class Soez5008ServiceImpl extends BaseServiceImpl implements Soez5008Service {

	private static NumberFormat numberFormat = new DecimalFormat("##,###");
	protected Logger logger = LoggerFactory.getLogger(this.getClass());


	@Resource(name="soez5008Dao")
	private Soez5008Dao soez5008Dao;

	@Resource(name="groupDao")
	private GroupDao groupDao;

	@Resource(name="codeTableDao")
	private CodeTableDao codeTableDao;


	@Resource(name="paymentDao")
	private PaymentDao paymentDao;

	@Resource(name="commissionCodeTableDao")
	public CommissionCodeTableDao commissionCodeTableDao;

	@Resource(name="realAccountDao")
	private RealAccountDao realAccountDao;

	/**
	 * 暫存目錄
	 */
	@Resource(name = "tempDirectory")
	private String tempDirectory;

	/*TODO  jeff 原本的取得COMMISSCODES 無法區分群組 需 @Deprecated */
	@Deprecated
	public List queryFeedbackLog(String channel, String code, Date qryDateFrom, Date qryDateTo)
	{
		if (null != qryDateFrom)
		{
			// 將時分秒設定在00:00:00
			qryDateFrom = DateUtil.getBeginOfDateTime(qryDateFrom);
		}

		if (null != qryDateTo)
		{
			// 將時分秒設定在23:59:59
			qryDateTo = DateUtil.getEndOfDateTime(qryDateTo);
		}

		if(channel != null)
		{
			//List commissionCodes = paymentDao.queryPaymentCommissionCode(channel, qryDateFrom, qryDateTo);
			List fbLogList = soez5008Dao.queryFeedbackLog(channel, code, qryDateFrom, qryDateTo);
			if(fbLogList != null && fbLogList.size() != 0)
			{
				//				for(int c=0;c<fbLogList.size();c++)
				//				{
				//					String commissionCode = (String)commissionCodes.get(c);
				//					String commissionCode = (String)((Map)commissionCodes.get(c)).get("commission_code");
				//					commissionCodes.set(c, commissionCode);
				//				}
				return fbLogList;
			}
		}
		return null;
	}
	/*TODO  jeff 原本的取得COMMISSCODES 無法區分群組 需 @Deprecated */
	@Deprecated
	public List queryCommissionCodes(String channel, Date qryDateFrom, Date qryDateTo)
	{
		if (null != qryDateFrom)
		{
			// 將時分秒設定在00:00:00
			qryDateFrom = DateUtil.getBeginOfDateTime(qryDateFrom);
		}

		if (null != qryDateTo)
		{
			// 將時分秒設定在23:59:59
			qryDateTo = DateUtil.getEndOfDateTime(qryDateTo);
		}

		if(channel != null)
		{
			//List commissionCodes = paymentDao.queryPaymentCommissionCode(channel, qryDateFrom, qryDateTo);
			List commissionCodes = soez5008Dao.queryCommissionCode(channel, qryDateFrom, qryDateTo);
			if(commissionCodes != null && commissionCodes.size() != 0)
			{
				for(int c=0;c<commissionCodes.size();c++)
				{
					//String commissionCode = (String)commissionCodes.get(c);
					String code = (String)((Map)commissionCodes.get(c)).get("code");
					commissionCodes.set(c, code);
				}
				return commissionCodes;
			}
		}
		return null;
	}

	//2011.12 by Leo
	/*    public Long sumFeedBackLogSubAmount(Group group ,List feedbackLogs, String type)
    {

    	Long resultAmount = new Long(0);
    	//1 算實撥金額
    	if(type.equals("1"))
    	{
	    	for(Iterator f=feedbackLogs.iterator();f.hasNext();)
	    	{
	    		Map feedBackMap = (Map)f.next();
	    		CommissionCodeTable commissionCodeTable = null;
	    		String commission = ((String)feedBackMap.get("BARCDOE1")).substring(6,9);
	            Long txamt = new Long(String.valueOf(feedBackMap.get("TXAMT")));

	           	 只對映超商代碼，不管帳單業者 
	            commissionCodeTable = commissionCodeTableDao.getCommissionCodeTable(commission);

	            if(commissionCodeTable != null && commissionCodeTable.getCommissionType().equals("I"))
	            	resultAmount = resultAmount + (txamt - commissionCodeTable.getGroupAmount());
	            else
	            	resultAmount = resultAmount + txamt;

	    	}
    	}else if(type.equals("2"))//2算繳款金額
    	{
    		for(Iterator f=feedbackLogs.iterator();f.hasNext();)
	    	{
	    		Map feedBackMap = (Map)f.next();
	    		CommissionCodeTable commissionCodeTable = null;
	    		String commission = ((String)feedBackMap.get("BARCDOE1")).substring(6,9);
	            Long txamt = new Long(String.valueOf(feedBackMap.get("TXAMT")));

	            resultAmount = resultAmount + txamt;

	    	}
    	}

    	return resultAmount;
    }
	 */    

	/*    @Override
    public List queryStaticsByChainstoreData(
    		String channel, Date qryDateFrom, Date qryDateTo,String commissionCode, List commissionCodes)
    {
    	if (null != qryDateFrom)
        {
            // 將時分秒設定在00:00:00
    		qryDateFrom = DateUtil.getBeginOfDateTime(qryDateFrom);
        }

        if (null != qryDateTo)
        {
            // 將時分秒設定在23:59:59
        	qryDateTo = DateUtil.getEndOfDateTime(qryDateTo);
        }

    	List results = new ArrayList();

		List resultSums = null;
		if(commissionCodes == null)
			//resultSums = paymentDao.sumChainstoreAmount(channel, qryDateFrom, qryDateTo, commissionCode,null);
			resultSums = soez5008Dao.sumChainstoreAmount(channel, qryDateFrom, qryDateTo, commissionCode, null);
		else
			//resultSums = paymentDao.sumChainstoreAmount(channel, qryDateFrom, qryDateTo, null,commissionCodes);
			resultSums = soez5008Dao.sumChainstoreAmount(channel, qryDateFrom, qryDateTo, null, commissionCodes);


       	// 取得手續費
		long groupAmount =0L;
		CommissionCodeTable commissionCodeTable = commissionCodeTableDao.getCommissionCodeTable(commissionCode);
		if (commissionCodeTable!=null)       	            
			groupAmount = commissionCodeTable.getGroupAmount();


		for(Iterator s=resultSums.iterator();s.hasNext();)
		{
			Map resultObject = (Map)s.next();
			Integer payedCount = (Integer)resultObject.get("count");
			BigDecimal payedTotalAmount = (BigDecimal)resultObject.get("txamt");
			BigDecimal payedTotalRealPayAmount = BigDecimal.valueOf(payedTotalAmount.longValue() - payedCount.intValue()*groupAmount);

//			String groupName = (String)resultObject[3];
//			BigDecimal groupPk = (BigDecimal)resultObject[4];
//			Group group = new Group();
//			group.setGroupName(groupName);
//			group.setGroupPk(new Long(groupPk.longValue()));

//			List feedbackLogs = null;
//			if(commissionCode == null)
//				feedbackLogs = soez5008Dao.queryFeedBackLog(group, qryDateFrom, qryDateTo, channel, null);
//			else
//				feedbackLogs = soez5008Dao.queryFeedBackLog(group, qryDateFrom, qryDateTo, channel, commissionCode);


//			Integer payedCount  = payedCount + feedbackLogs.size();

			SoezListBean bean = new SoezListBean();
//			bean.setGroup(group);
			bean.setPayedCount(new Long(payedCount.longValue())); //待收筆數
			bean.setPayedTotalAmount(new Long(payedTotalAmount.longValue()) ); //待收金額
			bean.setAvbal(groupAmount*payedCount); //待收手續費
			bean.setPayedTotalRealPayAmount(payedTotalAmount.longValue()-groupAmount*payedCount); //實撥金額

			results.add(bean);
		}
    	return results;
    }
	 */    
	//2011.12 by Leo
	/*    @Override
    public List queryStatisticsByGroup(Group group, Date qryDateFrom, Date qryDateTo)
    {
    	List results = new ArrayList();
    	List groups = groupDao.queryChainstoreStatistics(group, qryDateFrom, qryDateTo);
    	if(groups != null && groups.size() >0)
    	{
    		for(Iterator g=groups.iterator();g.hasNext();)
    		{
    			Group gp = (Group)g.next();
    			RealAccount entity = new RealAccount();
    			entity.setGroup(gp);
    			List accounts = realAccountDao.queryByGroup(entity);
    			//
    			if(accounts != null && accounts.size() >0)
    			{
    				for(Iterator a=accounts.iterator();a.hasNext();)
    				{
    					RealAccount account = (RealAccount)a.next();
    					Object[] resultObject = paymentDao.getStatisticsByGroupAccount(
    							gp, qryDateFrom, qryDateTo, account.getVirtualAccountNo());
    					SoezListBean listBean = new SoezListBean();
    					if(resultObject == null)
    					{
   						List feedbackLogs = soez5008Dao.queryFeedBackLog(gp, qryDateFrom, qryDateTo, null, null);
    						if(feedbackLogs == null && feedbackLogs.size() == 0)
    						{
	    						listBean.setGroup(gp);
	    						listBean.setRealAccount(account);
	    						listBean.setPayedCount(new Long(0));
	    						listBean.setPayedTotalAmount(new Long(0));
	    						listBean.setPayedTotalRealPayAmount(new Long(0));
    						}else
    						{
    							List feeds = new ArrayList();
    							for(Iterator f=feedbackLogs.iterator();f.hasNext();)
    					    	{
    					    		Map feedBackMap = (Map)f.next();
    					    		CommissionCodeTable commissionCodeTable = null;
    					    		String realAccount = ((String)feedBackMap.get("BARCDOE2")).substring(0,4);
    					            if(realAccount.equals(account.getVirtualAccountNo()))
    					            {
    					            	feeds.add(feedBackMap);
    					            }
    					    	}
    							listBean.setGroup(gp);
	    						listBean.setRealAccount(account);
    							listBean.setPayedCount(new Long(feeds.size()));
    							listBean.setPayedTotalAmount(sumFeedBackLogSubAmount(gp, feeds, "2"));
	    						listBean.setPayedTotalRealPayAmount(sumFeedBackLogSubAmount(gp, feeds, "1"));
    						}

    					}else
    					{
    						Integer payedCount = (Integer)resultObject[0];
	    					BigDecimal payedTotalAmount = (BigDecimal)resultObject[1];
	    					BigDecimal payedTotalRealPayAmount = (BigDecimal)resultObject[2];

    						List feedbackLogs = soez5008Dao.queryFeedBackLog(gp, qryDateFrom, qryDateTo, null, null);

    						Long count = new Long(0);
							Long ta = new Long(0);
							Long rta = new Long(0);
							if(feedbackLogs != null && feedbackLogs.size() >0)
							{
								List feeds = new ArrayList();
    							for(Iterator f=feedbackLogs.iterator();f.hasNext();)
    					    	{
    					    		Map feedBackMap = (Map)f.next();
    					    		CommissionCodeTable commissionCodeTable = null;
    					    		String realAccount = ((String)feedBackMap.get("BARCDOE2")).substring(0,4);
    					            if(realAccount.equals(account.getVirtualAccountNo()))
    					            {
    					            	feeds.add(feedBackMap);
    					            }
    					    	}
    							count = new Long(feeds.size());
    							ta = sumFeedBackLogSubAmount(gp, feeds, "2");
    							rta = sumFeedBackLogSubAmount(gp, feeds, "1");
							}
    						listBean.setGroup(gp);
    						listBean.setRealAccount(account);
    						listBean.setPayedCount(new Long(payedCount.intValue()) + count);
    						listBean.setPayedTotalAmount(new Long(payedTotalAmount.longValue()) + ta);
    						listBean.setPayedTotalRealPayAmount(new Long(payedTotalRealPayAmount.longValue()) + rta);


    					}
    					results.add(listBean);
    				}
    			}
    		}
    	}
    	return results;
    }
	 */
	/*    protected Map<String,Map<String, List<Map<String, Object>> > >preProcess(List<Map<String, Object>> dbRecords)
    {
        Map<String, Map<String, List<Map<String, Object>> >> nresult = new LinkedCaseInsensitiveMap<Map<String, List<Map<String, Object>> >> ();
        Map<String, Map<String, Map<String, Object>>> nchannelSubTotals = new LinkedCaseInsensitiveMap<Map<String, Map<String, Object>>>();

        Map<String, List<Map<String, Object>> > result = new LinkedCaseInsensitiveMap<List<Map<String,Object>>>();
        Map<String, Map<String, Object>> channelSubTotals = new LinkedCaseInsensitiveMap<Map<String, Object>>();

        for(Map<String, Object> dbRecord : dbRecords )
        {
            String writeOffDate = (String)dbRecord.get("WRITE_OFF_DATE");
            String channel = (String)dbRecord.get("CHANNEL");
            String channelName = (String)dbRecord.get("CHANNEL_NAME");
            String commissionCode = (String)dbRecord.get("COMMISSION_CODE");
            //Long commissionCodePk = new Long(String.valueOf(dbRecord.get("COMMISSION_CODE_PK")));
            String commissionCodeName = (String)dbRecord.get("COMMISSION_CODE_NAME");
            Long recordCount = new Long(String.valueOf(dbRecord.get("RECORD_COUNT")));
            Long amount = new Long(String.valueOf(dbRecord.get("AMOUNT")));
            Long commissionAmount = new Long(String.valueOf(dbRecord.get("COMMISSION_AMOUNT")));
            Long realAmount = new Long(String.valueOf(dbRecord.get("REAL_AMOUNT")));




            //date

            result = nresult.get(writeOffDate);
            if (null == result)
            {
                result = new LinkedCaseInsensitiveMap<List<Map<String, Object>> >();
                nresult.put(writeOffDate, result);                
            }


            // 依據通路歸類資料
            List<Map<String, Object>> data = result.get(channel);
            if (null == data)
            {
                data = new ArrayList<Map<String,Object>>();
                result.put(channel, data);                
            }


            Map<String, Object> toAddInData = new LinkedCaseInsensitiveMap<Object>();

            toAddInData.put("CHANNEL", channel);
            toAddInData.put("CHANNEL_NAME", channelName);
            toAddInData.put("COMMISSION_CODE", commissionCode);
            toAddInData.put("COMMISSION_CODE_NAME", commissionCodeName);
            toAddInData.put("RECORD_COUNT", recordCount);
            toAddInData.put("AMOUNT", amount);
            toAddInData.put("COMMISSION_AMOUNT", commissionAmount);   
            toAddInData.put("REAL_AMOUNT", realAmount);
            data.add(toAddInData);

            // 累計

            channelSubTotals = nchannelSubTotals.get(writeOffDate);

            if (null == channelSubTotals)
            {
                channelSubTotals = new LinkedCaseInsensitiveMap<Map<String, Object>>();
                nchannelSubTotals.put(writeOffDate, channelSubTotals);              
            }

            Map<String, Object> channelSubTotal = channelSubTotals.get(channel);
            if (null == channelSubTotal)
            {
                channelSubTotal = new LinkedCaseInsensitiveMap<Object>();
                channelSubTotal.put("CHANNEL", channel);
                channelSubTotal.put("CHANNEL_NAME", channelName);
                channelSubTotal.put("COMMISSION_CODE", "小計");

                channelSubTotal.put("COMMISSION_CODE_NAME", "");

                channelSubTotal.put("RECORD_COUNT", recordCount);
                channelSubTotal.put("AMOUNT", amount);
                channelSubTotal.put("COMMISSION_AMOUNT", commissionAmount);  
                channelSubTotal.put("REAL_AMOUNT", realAmount);

                channelSubTotals.put(channel, channelSubTotal);
                nchannelSubTotals.put(writeOffDate, channelSubTotals);
            }
            else
            {
                channelSubTotal.put("RECORD_COUNT", (Long)channelSubTotal.get("RECORD_COUNT") + recordCount);
                channelSubTotal.put("AMOUNT", (Long)channelSubTotal.get("AMOUNT") + amount);
                channelSubTotal.put("COMMISSION_AMOUNT", (Long)channelSubTotal.get("COMMISSION_AMOUNT") + commissionAmount);  
                channelSubTotal.put("REAL_AMOUNT", (Long)channelSubTotal.get("REAL_AMOUNT") + realAmount);
            }
        }

        // 將個別的累計放在個別資料集合的最後一筆資料
        Iterator<String> writeOffDateIt = nresult.keySet().iterator();
        while(writeOffDateIt.hasNext())
        {
            String writeOffDate = writeOffDateIt.next();
            result = nresult.get(writeOffDate);
            channelSubTotals = nchannelSubTotals.get(writeOffDate);
            Iterator<String> channelIt = result.keySet().iterator();
            while(channelIt.hasNext())
            {
                String channel = channelIt.next();
                result.get(channel).add(channelSubTotals.get(channel));            
            }
        }

        if (null != nchannelSubTotals)
            nchannelSubTotals.clear();

        return nresult;

    }
	 */
	/* (non-Javadoc)
	 * @see com.feib.soeasy.service.Soez5008Service#queryForList(com.feib.soeasy.model.Group, java.lang.Integer, java.util.Date, java.util.Date)
	 */
	/*    @Override
    public Map<String,Map<String, List<Map<String, Object>>>>queryForStatisticsList(Group group, Integer qryDateType, Date dateFrom, Date dateTo) {

        if (null != dateFrom)
        {
            // 將時分秒設定在00:00:00
            dateFrom = DateUtil.getBeginOfDateTime(dateFrom);
        }

        if (null != dateTo)
        {
            // 將時分秒設定在23:59:59
            dateTo = DateUtil.getEndOfDateTime(dateTo);
        }

        Group dbGroup = null;
        if (null != group && StringUtils.isNotEmpty(group.getGroupNo()))
        {
            dbGroup = groupDao.findByGroupNo(group.getGroupNo());
            group.setGroupPk(dbGroup.getGroupPk());
            group.setGroupName(dbGroup.getGroupName());
        }

        // WriteOffPayment.CHANNEL_7_11
        List<Map<String, Object>> dbRecords = soez5008Dao.getStatisticsForStore((null==dbGroup ?null:dbGroup.getGroupPk()), null, qryDateType, dateFrom, dateTo);

        //只須超商資料
        //List<Map<String, Object>> dbRecords2 = soez5008Dao.getStatisticsForNotStore(dbGroup.getGroupPk(), null, qryDateType, dateFrom, dateTo);

        //dbRecords.addAll(dbRecords2);


        if (null == dbRecords || 0 == dbRecords.size())
            return null;

        return this.preProcess(dbRecords);
    }
	 */    
	@Override
	public String doAjaxQueryCommissionCodeXls(String channel, String commissionCode, Date qryDateFrom, Date qryDateTo )
	{
		List results = queryFeedbackLogByChannelCommission(channel, commissionCode, qryDateFrom, qryDateTo);
		//TODO
		//串欄位表頭
		String[] titles = {
				"傳輸日期","超商","CODE","繳費期限","繳費日期" ,"帳單業者", "繳費帳號", "繳費金額" , "代收手續費","實撥金額"};

		Workbook wb = new HSSFWorkbook(); // 若要產生xlsx則使用 XSSFWorkbook 即可
		Map<String, CellStyle> styles = createStyles(wb);

		Sheet sheet = wb.createSheet("超商傳輸統計明細表");
		PrintSetup printSetup = sheet.getPrintSetup();
		printSetup.setLandscape(true);
		sheet.setFitToPage(true);
		sheet.setHorizontallyCenter(true);
		sheet.setZoom(3, 4);
		sheet.setColumnWidth(0, 256*20);
		sheet.setColumnWidth(1, 256*15);
		sheet.setColumnWidth(2, 256*20);
		sheet.setColumnWidth(3, 256*40);
		sheet.setColumnWidth(4, 256*25);
		sheet.setColumnWidth(5, 256*20);
		sheet.setColumnWidth(6, 256*15);
		sheet.setColumnWidth(7, 256*20);


		// 行數
		int rownum = 0;


		/* 效能提升  超商／郵局傳輸統計查詢  總計記數 */
		Long totalCount = new Long(0);
		Long totalAmount = new Long(0);
		Long totalFee = new Long(0);
		Long totalRealAmount = new Long(0);


		//title row
		Row titleRow = sheet.createRow(rownum++);
		titleRow.setHeightInPoints((float)32.25);
		Cell titleCell = titleRow.createCell(0);
		titleCell.setCellValue("超商／郵局傳輸統計明細表");
		titleCell.setCellStyle(styles.get("title"));
		sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$H$1"));

		Row blankRow = sheet.createRow(rownum++);
		blankRow.setHeightInPoints((float)18);

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");

		//超商日期資料
		if(channel != null && !"".equals(channel))
		{
			Row dataRow = sheet.createRow(rownum++);
			Cell dataCell;
			dataCell = dataRow.createCell(0);
			dataCell.setCellValue(codeTableDao.getCodeTable("CHANEL", channel).getCodeName() + "：" + dateFormat.format(qryDateFrom)+"～" + dateFormat.format(qryDateTo) + "  代碼 : "+commissionCode);
			dataCell.setCellStyle(styles.get("title2"));
			sheet.addMergedRegion(CellRangeAddress.valueOf("$A$"+rownum+":$G$" + rownum));
		}

		//欄位表頭
		Row headerRow = sheet.createRow(rownum++);
		headerRow.setHeightInPoints((float) 25.5);
		Cell headerCell;
		for (int i = 0; i < titles.length; i++) {
			headerCell = headerRow.createCell(i);
			headerCell.setCellValue(titles[i]);
			headerCell.setCellStyle(styles.get("header"));
		}


		int no = 1;
		for(Iterator i=results.iterator();i.hasNext();)
		{
			Map fblog = (Map)i.next();


			/* 效能提升  超商／郵局傳輸統計查詢   總計記數 個別Code統計值 */
			Long codeCount = new Long(0);
			Long codeAmount = new Long(0);
			Long codeFee = new Long(0);
			Long codeRealAmount = new Long(0);

			codeCount++;			
			long txamt = ((BigDecimal)fblog.get("txamt")).longValue();  
			codeAmount += txamt;
			codeFee+= ((Long)fblog.get("fee")).longValue();
			codeRealAmount+=((BigDecimal)fblog.get("txamt")).longValue()-((Long)fblog.get("fee")).longValue();
			Row dataRow = sheet.createRow(rownum++);
			Cell dataCell;
			dataCell = dataRow.createCell(0);
			String fbDate = (String)fblog.get("fbdate");
			dataCell.setCellValue(fbDate.substring(0,4)+"/"+fbDate.substring(4,6)+"/"+fbDate.substring(6,8));
			dataCell.setCellStyle(styles.get("cell_date"));
			dataCell = dataRow.createCell(1);
			Date dueday = (Date)fblog.get("dueday");
			if (dueday==null)
				dataCell.setCellValue("N/A");
			else
				dataCell.setCellValue(dateFormat.format(dueday));
			dataCell.setCellStyle(styles.get("cell_date"));

			/* 效能提升  超商／郵局傳輸統計查詢  總計記數 */
			dataCell = dataRow.createCell(2);
			dataCell.setCellValue(codeTableDao.getCodeTable("CHANEL", channel).getCodeName());
			dataCell.setCellStyle(styles.get("cell"));
			dataCell = dataRow.createCell(3);
			dataCell.setCellValue(commissionCode);



			dataCell = dataRow.createCell(4);
			String aday = (String)fblog.get("aday");
			dataCell.setCellValue(aday.substring(0,4)+"/"+aday.substring(4,6)+"/"+aday.substring(6,8));
			dataCell.setCellStyle(styles.get("cell_date"));
			dataCell = dataRow.createCell(5);
			dataCell.setCellValue((String)fblog.get("gpname"));
			dataCell.setCellStyle(styles.get("cell"));
			dataCell = dataRow.createCell(6);
			dataCell.setCellValue((String)fblog.get("userno"));
			dataCell.setCellStyle(styles.get("cell"));
			dataCell = dataRow.createCell(7);
			dataCell.setCellValue(((BigDecimal)fblog.get("txamt")).longValue());
			dataCell.setCellStyle(styles.get("cell_number"));
			dataCell = dataRow.createCell(8);
			dataCell.setCellValue(((Long)fblog.get("fee")).longValue());
			dataCell.setCellStyle(styles.get("cell_number"));
			dataCell = dataRow.createCell(9);
			dataCell.setCellValue(((BigDecimal)fblog.get("txamt")).longValue()-((Long)fblog.get("fee")).longValue());
			dataCell.setCellStyle(styles.get("cell_number"));
			no++; 
			/* 效能提升  超商／郵局傳輸統計查詢  總計記數 */
			totalCount += codeCount;
			totalAmount += codeAmount;
			totalFee += codeFee;
			totalRealAmount += codeRealAmount;

		}

		Row dataRow = sheet.createRow(rownum++);
		Cell dataCell;

		dataCell = dataRow.createCell(0);
		dataCell.setCellStyle(styles.get("cell"));
		dataCell = dataRow.createCell(1);				
		dataCell.setCellStyle(styles.get("cell"));	
		dataCell = dataRow.createCell(2);						
		dataCell.setCellStyle(styles.get("cell"));
		dataCell = dataRow.createCell(3);						
		dataCell.setCellStyle(styles.get("cell"));
		dataCell = dataRow.createCell(4);						
		dataCell.setCellStyle(styles.get("cell"));
		/* 效能提升  超商／郵局傳輸統計查詢  總計記數 */
		dataCell = dataRow.createCell(5);						
		dataCell.setCellStyle(styles.get("cell"));
		dataCell.setCellValue("總計");
		dataCell = dataRow.createCell(6);
		dataCell.setCellValue(totalCount+"筆");
		dataCell.setCellStyle(styles.get("cell_ALIGN_RIGHT"));
		dataCell = dataRow.createCell(7);
		dataCell.setCellValue(totalAmount);
		dataCell.setCellStyle(styles.get("cell_number"));
		dataCell = dataRow.createCell(8);
		dataCell.setCellValue(totalFee);
		dataCell.setCellStyle(styles.get("cell_number"));
		dataCell = dataRow.createCell(9);
		dataCell.setCellValue(totalRealAmount);
		dataCell.setCellStyle(styles.get("cell_number"));



		int colCount = 0;
		/* 效能提升  超商／郵局傳輸統計查詢  總計記數 */
		while (colCount <= titles.length) {
			sheet.autoSizeColumn((short) colCount++,true);//自動調整欄寬
		}


		String tempDownloadFilePath = tempDirectory + "/" + UserUtil.getUserGroup().getGroupNo() + "/" + UserUtil.getUserId() + "/";
		File directory = new File(tempDownloadFilePath);             
		if(!directory.exists())
		{
			try {
				FileUtils.forceMkdir(directory);
			}
			catch (IOException e) {
				logger.error("{}",e);
			}
		}

		String fileFullName = tempDownloadFilePath + UUID.randomUUID().toString() + "-超商傳輸統計明細表.xls";

		FileOutputStream out;
		try {
			out = new FileOutputStream(fileFullName);
			wb.write(out);
			out.close();
		}
		catch (FileNotFoundException e) {
			logger.error("{}",e);
		}
		catch (IOException e) {
			logger.error("{}",e);
		}
		return fileFullName;
	}

	/*    @Override
    public String doExportStatisticsByGroupXls(Group group, Date qryDateFrom, Date qryDateTo)
    {
    	List results = queryStatisticsByGroup(group, qryDateFrom, qryDateTo);

    	//串欄位表頭
        String[] titles = {
        		"No.","業者代號","入帳帳號" ,"業者名稱", "代收筆數", "代收金額" , "實撥金額"};

        Workbook wb = new HSSFWorkbook(); // 若要產生xlsx則使用 XSSFWorkbook 即可
        Map<String, CellStyle> styles = createStyles(wb);

        Sheet sheet = wb.createSheet("超商代收統計表");
        PrintSetup printSetup = sheet.getPrintSetup();
        printSetup.setLandscape(true);
        sheet.setFitToPage(true);
        sheet.setHorizontallyCenter(true);
        sheet.setZoom(3, 4);
        sheet.setColumnWidth(1, 256*20);
        sheet.setColumnWidth(2, 256*20);
        sheet.setColumnWidth(3, 256*25);
        sheet.setColumnWidth(5, 256*20);
        sheet.setColumnWidth(6, 256*20);


     // 行數
        int rownum = 0;

      //title row
        Row titleRow = sheet.createRow(rownum++);
        titleRow.setHeightInPoints((float)32.25);
        Cell titleCell = titleRow.createCell(0);
        titleCell.setCellValue("超商代收統計表");
        titleCell.setCellStyle(styles.get("title"));
        sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$G$1"));

        Row blankRow = sheet.createRow(rownum++);
        blankRow.setHeightInPoints((float)18);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");

        Row headerRow = sheet.createRow(rownum++);
        headerRow.setHeightInPoints((float) 25.5);
        Cell headerCell;
        for (int i = 0; i < titles.length; i++) {
            headerCell = headerRow.createCell(i);
            headerCell.setCellValue(titles[i]);
            headerCell.setCellStyle(styles.get("header"));
        }
        int no = 1;
        for(Iterator i=results.iterator();i.hasNext();)
        {
        	SoezListBean bean = (SoezListBean)i.next();

        	Row dataRow = sheet.createRow(rownum++);
			Cell dataCell;
			dataCell = dataRow.createCell(0);
			dataCell.setCellValue(String.valueOf(no++));
			dataCell.setCellStyle(styles.get("cell"));
			dataCell = dataRow.createCell(1);
			dataCell.setCellValue(bean.getGroup().getGroupNo());
			dataCell.setCellStyle(styles.get("cell"));
			dataCell = dataRow.createCell(2);
			dataCell.setCellValue(bean.getRealAccount().getAccountNo());
			dataCell.setCellStyle(styles.get("cell"));
			dataCell = dataRow.createCell(3);
			dataCell.setCellValue(bean.getGroup().getGroupName());
			dataCell.setCellStyle(styles.get("cell"));
			dataCell = dataRow.createCell(4);
			dataCell.setCellValue(bean.getPayedCount());
			dataCell.setCellStyle(styles.get("cell"));
			dataCell = dataRow.createCell(5);
			dataCell.setCellValue(bean.getPayedTotalAmount());
			dataCell.setCellStyle(styles.get("cell_number"));
			dataCell = dataRow.createCell(6);
			dataCell.setCellValue(bean.getPayedTotalRealPayAmount());
			dataCell.setCellStyle(styles.get("cell_number"));

        }


    	String tempDownloadFilePath = tempDirectory + "/" + UserUtil.getUserGroup().getGroupNo() + "/" + UserUtil.getUserId() + "/";
        File directory = new File(tempDownloadFilePath);             
        if(!directory.exists())
        {
            try {
                FileUtils.forceMkdir(directory);
            }
            catch (IOException e) {
                logger.error("{}",e);
            }
        }

        String fileFullName = tempDownloadFilePath + UUID.randomUUID().toString() + "-帳單通路統計表.xls";

        FileOutputStream out;
        try {
            out = new FileOutputStream(fileFullName);
            wb.write(out);
            out.close();
        }
        catch (FileNotFoundException e) {
            logger.error("{}",e);
        }
        catch (IOException e) {
            logger.error("{}",e);
        }
        return fileFullName;

    }
	 */    
	/*TODO JEFF 原本的畫面顯示 無法區分群組 需 @Deprecated*/
	@Deprecated
	public String doExportStatisticsXls(String[] channels, Date[] dateFroms, Date[] dateTos)
	{
		Workbook wb = new HSSFWorkbook(); // 若要產生xlsx則使用 XSSFWorkbook 即可
		Map<String, CellStyle> styles = createStyles(wb);

		Sheet sheet = wb.createSheet("超商傳輸統計表");
		PrintSetup printSetup = sheet.getPrintSetup();
		printSetup.setLandscape(true);
		sheet.setFitToPage(true);
		sheet.setHorizontallyCenter(true);
		sheet.setZoom(3, 4);
		sheet.setColumnWidth(0, 256*25);
		sheet.setColumnWidth(1, 256*10);
		sheet.setColumnWidth(3, 256*20);
		sheet.setColumnWidth(4, 256*20);
		sheet.setColumnWidth(5, 256*20);
		sheet.setColumnWidth(6, 256*20);


		// 行數
		int rownum = 0;

		//title row
		Row titleRow = sheet.createRow(rownum++);
		titleRow.setHeightInPoints((float)32.25);
		Cell titleCell = titleRow.createCell(0);
		titleCell.setCellValue("超商／郵局傳輸統計表");
		titleCell.setCellStyle(styles.get("title"));
		sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$G$1"));

		Row blankRow = sheet.createRow(rownum++);
		blankRow.setHeightInPoints((float)18);

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");

		for(int i=0;i<channels.length;i++)
		{
			String channel = channels[i];
			Date dateFrom = dateFroms[i];
			Date dateTo = dateTos[i];
			if(channel != null && !"".equals(channel))
			{
				Row dataRow = sheet.createRow(rownum++);
				Cell dataCell;
				dataCell = dataRow.createCell(0);
				dataCell.setCellValue(codeTableDao.getCodeTable("CHANEL", channel).getCodeName() + "：" + dateFormat.format(dateFrom)+"～" + dateFormat.format(dateTo));
				dataCell.setCellStyle(styles.get("title2"));
				sheet.addMergedRegion(CellRangeAddress.valueOf("$A$"+rownum+":$G$" + rownum));
			}

		}


		//串欄位表頭
		String[] titles = {
				"傳輸日期","超商","CODE" ,"代收筆數", "代收金額" , "代收手續費", "實撥金額"};

		Row headerRow = sheet.createRow(rownum++);
		headerRow.setHeightInPoints((float) 25.5);
		Cell headerCell;



		for (int i = 0; i < titles.length; i++) {
			headerCell = headerRow.createCell(i);
			headerCell.setCellValue(titles[i]);
			headerCell.setCellStyle(styles.get("header"));
		}

		//總計數據
		Long totalCount = new Long(0);
		Long totalAmount = new Long(0);
		Long totalFee = new Long(0);
		Long totalRealAmount = new Long(0);

		//      Long mainCount = new Long(0);
		//    	Long mainTotalAmount = new Long(0);
		//    	Long mainRealAmount = new Long(0);
		String cellRangeAddress = null;

		for(int i=0;i<channels.length;i++)
		{
			String channel = channels[i];
			Date dateFrom = dateFroms[i];
			Date dateTo = dateTos[i];
			int start = 0;

			//個別超商統計值
			Long channelCount = new Long(0);
			Long channelAmount = new Long(0);
			Long channelFee = new Long(0);
			Long channelRealAmount = new Long(0);

			List commissionCodes = this.queryCommissionCodes(channel, dateFrom, dateTo);
			if(commissionCodes == null)
			{
				if(channel != null && !"".equals(channel))
				{
					Row dataRow = sheet.createRow(rownum++);
					Cell dataCell;
					dataCell = dataRow.createCell(0);
					dataCell.setCellValue(dateFormat.format(dateFrom)+"～" + dateFormat.format(dateTo));
					dataCell.setCellStyle(styles.get("cell"));
					dataCell = dataRow.createCell(1);
					dataCell.setCellValue(codeTableDao.getCodeTable("CHANEL", channel).getCodeName());
					dataCell.setCellStyle(styles.get("cell"));
					dataCell = dataRow.createCell(2);
					dataCell.setCellValue("查無資料 ");
					dataCell.setCellStyle(styles.get("cell"));
					sheet.addMergedRegion(CellRangeAddress.valueOf("$C$"+rownum+":$G$" + rownum));
				}
			}else
			{
				start = rownum + 1;
				for(Iterator cis=commissionCodes.iterator();cis.hasNext();)
				{
					String code = (String)cis.next();

					// 取得超商(不含郵局)符合Code手續費
					long fee =0L;
					if (!channel.equals("H")) //非郵局
					{	
						CommissionCodeTable commissionCodeTable = commissionCodeTableDao.getCommissionCodeTable(code);
						if (commissionCodeTable!=null)       	            
							fee = commissionCodeTable.getGroupAmount();
					}

					//取得符合channel與commissionCode的每筆Feedback Log資料,組成統計值
					List fbLogs = this.queryFeedbackLog(channel, code, dateFrom, dateTo);

					//個別Code統計值
					Long codeCount = new Long(0);
					Long codeAmount = new Long(0);
					Long codeFee = new Long(0);
					Long codeRealAmount = new Long(0);

					for(Iterator iter=fbLogs.iterator();iter.hasNext();)
					{
						codeCount++;
						Map fblog = (Map)iter.next();
						long txamt = ((BigDecimal)fblog.get("txamt")).longValue();  
						codeAmount += txamt;
						//取得郵局手續費
						if (channel.equals("H")) //郵局
						{
							Group gp = getGroupByVirtualAccount((String)fblog.get("userno"));
							if (gp == null)
								fee = 0;
							else
							{	
								groupDao.findByPk((long)1);
								if (txamt<=100) fee = gp.getPostLevel1();
								else if (txamt<=1000) fee = gp.getPostLevel2();
								else if (txamt>1000) fee = gp.getPostLevel3();
							}	
						}
						codeFee += fee;
						codeRealAmount += txamt - fee;
					}

					if(fbLogs != null && fbLogs.size() >0)
					{
						int commissionStart = rownum + 1;

						Row dataRow = sheet.createRow(rownum++);
						Cell dataCell;
						dataCell = dataRow.createCell(0);
						dataCell.setCellValue(dateFormat.format(dateFrom)+"～" + dateFormat.format(dateTo));
						dataCell.setCellStyle(styles.get("cell"));
						dataCell = dataRow.createCell(1);
						dataCell.setCellValue(codeTableDao.getCodeTable("CHANEL", channel).getCodeName());
						dataCell.setCellStyle(styles.get("cell"));
						dataCell = dataRow.createCell(2);
						dataCell.setCellValue(code);
						dataCell.setCellStyle(styles.get("cell"));
						dataCell = dataRow.createCell(3);
						dataCell.setCellValue(codeCount);
						dataCell.setCellStyle(styles.get("cell_ALIGN_RIGHT"));
						dataCell = dataRow.createCell(4);
						dataCell.setCellValue(codeAmount);
						dataCell.setCellStyle(styles.get("cell_number"));
						dataCell = dataRow.createCell(5);
						dataCell.setCellValue(codeFee);
						dataCell.setCellStyle(styles.get("cell_number"));
						dataCell = dataRow.createCell(6);
						dataCell.setCellValue(codeRealAmount);
						dataCell.setCellStyle(styles.get("cell_number"));

						sheet.addMergedRegion(CellRangeAddress.valueOf("$C$"+commissionStart+":$C$" + rownum));
					}	

					//加統計值
					channelCount += codeCount;
					channelAmount += codeAmount;
					channelFee += codeFee;
					channelRealAmount += codeRealAmount;

				}

				/*
				List groupSumData = this.queryStaticsByChainstoreData(channel, dateFrom, dateTo, null, commissionCodes);
				Long count = new Long(0);
				Long totalAmount = new Long(0);
				Long realPayAmount = new Long(0);
				for(Iterator si=groupSumData.iterator();si.hasNext();)
				{
					SoezListBean bean = (SoezListBean)si.next();

					Row dataRow = sheet.createRow(rownum++);
					Cell dataCell;
					dataCell = dataRow.createCell(0);
					dataCell.setCellValue(dateFormat.format(dateFrom)+"～" + dateFormat.format(dateTo));
					dataCell.setCellStyle(styles.get("cell"));
					dataCell = dataRow.createCell(1);
					dataCell.setCellValue(codeTableDao.getCodeTable("CHANEL", channel).getCodeName());
					dataCell.setCellStyle(styles.get("cell"));

					dataCell = dataRow.createCell(2);
					dataCell.setCellValue(bean.getGroup().getGroupName());
					dataCell.setCellStyle(styles.get("cell"));
					sheet.addMergedRegion(CellRangeAddress.valueOf("$C$"+rownum+":$D$" + rownum));
					dataCell = dataRow.createCell(3);				
					dataCell.setCellStyle(styles.get("cell"));
					dataCell = dataRow.createCell(4);
					dataCell.setCellValue(bean.getPayedCount());
					dataCell.setCellStyle(styles.get("cell"));
					dataCell = dataRow.createCell(5);
					if(!channel.equals("H"))
						dataCell.setCellValue(bean.getPayedTotalAmount());
					else
						dataCell.setCellValue(bean.getPayedTotalRealPayAmount());

					dataCell.setCellStyle(styles.get("cell_number"));
					dataCell = dataRow.createCell(6);
					dataCell.setCellValue(bean.getPayedTotalRealPayAmount());
					dataCell.setCellStyle(styles.get("cell_number"));

					count = count + bean.getPayedCount();
					if(!channel.equals("H"))
					{
						totalAmount = totalAmount + bean.getPayedTotalAmount();
						realPayAmount = realPayAmount + bean.getPayedTotalRealPayAmount();
					}else{
						totalAmount = totalAmount + bean.getPayedTotalRealPayAmount();
						realPayAmount = realPayAmount + bean.getPayedTotalRealPayAmount();						
					}

				}
				 */				
				Row dataRow = sheet.createRow(rownum++);
				Cell dataCell;
				dataCell = dataRow.createCell(0);
				dataCell.setCellValue(dateFormat.format(dateFrom)+"～" + dateFormat.format(dateTo));
				dataCell.setCellStyle(styles.get("cell"));
				dataCell = dataRow.createCell(1);
				dataCell.setCellValue(codeTableDao.getCodeTable("CHANEL", channel).getCodeName());
				dataCell.setCellStyle(styles.get("cell"));

				dataCell = dataRow.createCell(2);				
				dataCell.setCellValue("統計");
				dataCell.setCellStyle(styles.get("cell"));
				//sheet.addMergedRegion(CellRangeAddress.valueOf("$C$"+rownum+":$D$" + rownum));

				/* 效能提升  超商／郵局傳輸統計查詢  總計記數 */
				dataCell = dataRow.createCell(3);
				dataCell.setCellValue(channelCount);
				dataCell.setCellStyle(styles.get("cell_ALIGN_RIGHT"));

				dataCell = dataRow.createCell(4);				
				dataCell.setCellValue(channelAmount);

				dataCell.setCellStyle(styles.get("cell_number"));
				dataCell = dataRow.createCell(5);
				dataCell.setCellValue(channelFee);
				dataCell.setCellStyle(styles.get("cell_number"));
				dataCell = dataRow.createCell(6);
				dataCell.setCellValue(channelRealAmount);
				dataCell.setCellStyle(styles.get("cell_number"));


				//總合計
				totalCount += channelCount;
				totalAmount += channelAmount;
				totalFee += channelFee;
				totalRealAmount += channelRealAmount;

				sheet.addMergedRegion(CellRangeAddress.valueOf("$A$"+start+":$A$" + rownum));
				sheet.addMergedRegion(CellRangeAddress.valueOf("$B$"+start+":$B$" + rownum));
			}



			//sheet.addMergedRegion(CellRangeAddress.valueOf(cellRangeAddress + ":$A$" + rownum));
		}

		Row dataRow = sheet.createRow(rownum++);
		Cell dataCell;
		sheet.addMergedRegion(CellRangeAddress.valueOf("$A$"+rownum+":$B$" + rownum));
		dataCell = dataRow.createCell(0);
		dataCell.setCellValue("總計");
		dataCell.setCellStyle(styles.get("cell"));
		dataCell = dataRow.createCell(1);				
		dataCell.setCellStyle(styles.get("cell"));

		//sheet.addMergedRegion(CellRangeAddress.valueOf("$C$"+rownum+":$D$" + rownum));

		dataCell = dataRow.createCell(2);				
		dataCell.setCellValue("超商／郵局合計");
		dataCell.setCellStyle(styles.get("cell"));
		/* 效能提升  超商／郵局傳輸統計查詢  總計記數 */
		dataCell = dataRow.createCell(3);
		dataCell.setCellValue(totalCount);
		dataCell.setCellStyle(styles.get("cell_ALIGN_RIGHT"));
		dataCell = dataRow.createCell(4);
		dataCell.setCellValue(totalAmount);
		dataCell.setCellStyle(styles.get("cell_number"));
		dataCell = dataRow.createCell(5);
		dataCell.setCellValue(totalFee);
		dataCell.setCellStyle(styles.get("cell_number"));
		dataCell = dataRow.createCell(6);
		dataCell.setCellValue(totalRealAmount);
		dataCell.setCellStyle(styles.get("cell_number"));



		int colCount = 0;
		/* 效能提升  超商／郵局傳輸統計查詢  總計記數 */
		while (colCount <= titles.length) {
			sheet.autoSizeColumn((short) colCount++,true);//自動調整欄寬
		}

		String tempDownloadFilePath = tempDirectory + "/" + UserUtil.getUserGroup().getGroupNo() + "/" + UserUtil.getUserId() + "/";
		File directory = new File(tempDownloadFilePath);             
		if(!directory.exists())
		{
			try {
				FileUtils.forceMkdir(directory);
			}
			catch (IOException e) {
				logger.error("{}",e);
			}
		}

		String fileFullName = tempDownloadFilePath + UUID.randomUUID().toString() + "-超商傳輸統計表.xls"; //

		FileOutputStream out;
		try {
			out = new FileOutputStream(fileFullName);
			wb.write(out);
			out.close();
		}
		catch (FileNotFoundException e) {
			logger.error("{}",e);
		}
		catch (IOException e) {
			logger.error("{}",e);
		}
		return fileFullName;
	}



	/*    private void writeExcelData(Sheet sheet, Map<String, CellStyle> styles, Map<String, Map<String, List<Map<String, Object>>>> dbData )
    {


        if (null != dbData && 0 != dbData.size())
        {


            //日期集合
            Set<String> dbDataKeys1=dbData.keySet();

            //通路
            String dbDataKeys[] = new String[]{WriteOffPayment.CHANNEL_7_11, WriteOffPayment.CHANNEL_FAMILY_MART
                            , WriteOffPayment.CHANNEL_OK_MART,WriteOffPayment.CHANNEL_HILIFE };


            //依日期取出
            for (String key1 :dbDataKeys1){


                Row dataRow = null;
                Cell cell = null;

                Boolean first=true; 
                String cellRangeAddress = null;

                int    rownum = sheet.getLastRowNum()+ 1;

                int count =0;

                //依通路取出 
                for (String key :dbDataKeys){    

                    List<Map<String, Object>>  channelDatas = dbData.get(key1).get(key);



                    if(null !=channelDatas && 0 != channelDatas.size())  {

                        count+= channelDatas.size();
                    }



                    if(null !=channelDatas && 0 != channelDatas.size())  {

                        String writeOffDate = key1;

                        for(Map<String, Object> channelData : channelDatas)
                        {
                            String channelName = (String)channelData.get("CHANNEL_NAME");
                            String commissionCode = (String)channelData.get("COMMISSION_CODE");
                            String commissionCodeName = (String)channelData.get("COMMISSION_CODE_NAME");
                            Long recordCount = (Long)channelData.get("RECORD_COUNT");
                            Long amount = (Long)channelData.get("AMOUNT");
                            Long commissionAmount = (Long)channelData.get("COMMISSION_AMOUNT");
                            Long realAmount = (Long)channelData.get("REAL_AMOUNT");

                            dataRow = sheet.createRow(rownum++);
                            if (null == cellRangeAddress)
                                cellRangeAddress = "$A$"+rownum;
                            dataRow.setHeightInPoints((float) 25);                    

                            if(commissionCode.equals("小計")){


                                cell = dataRow.createCell(1);
                                cell.setCellValue("");
                                cell.setCellStyle(styles.get("cell"));
                                // 代收代號
                                cell = dataRow.createCell(2);
                                cell.setCellValue(commissionCode);
                                cell.setCellStyle(styles.get("cell_total"));

                                // 代收類別
                                cell = dataRow.createCell(3);
                                cell.setCellValue(commissionCodeName);
                                cell.setCellStyle(styles.get("cell_total"));

                                // 每筆手續費
                                cell = dataRow.createCell(4);
                                cell.setCellValue("");
                                cell.setCellStyle(styles.get("cell_number_total"));

                                // 代收筆數
                                cell = dataRow.createCell(5);
                                cell.setCellValue(recordCount);
                                cell.setCellStyle(styles.get("cell_total"));

                                // 代收金額小計
                                cell = dataRow.createCell(6);
                                cell.setCellValue(amount);
                                cell.setCellStyle(styles.get("cell_number_total"));



                                // 實際入帳金額小計
                                cell = dataRow.createCell(7);
                                cell.setCellValue(realAmount);
                                cell.setCellStyle(styles.get("cell_number_total"));

                            }else{ 


                                cell = dataRow.createCell(1);
                                cell.setCellValue(channelName);
                                cell.setCellStyle(styles.get("cell"));


                                // 代收代號

                                cell = dataRow.createCell(2);
                                cell.setCellValue(commissionCode);
                                cell.setCellStyle(styles.get("cell"));

                                // 代收類別
                                cell = dataRow.createCell(3);
                                cell.setCellValue(commissionCodeName);
                                cell.setCellStyle(styles.get("cell"));

                                // 每筆手續費
                                cell = dataRow.createCell(4);
                                cell.setCellValue(commissionAmount);
                                cell.setCellStyle(styles.get("cell_number"));

                                // 代收筆數
                                cell = dataRow.createCell(5);
                                cell.setCellValue(recordCount);
                                cell.setCellStyle(styles.get("cell"));

                                // 代收金額小計
                                cell = dataRow.createCell(6);
                                cell.setCellValue(amount);
                                cell.setCellStyle(styles.get("cell_number"));



                                // 實際入帳金額小計
                                cell = dataRow.createCell(7);
                                cell.setCellValue(realAmount);
                                cell.setCellStyle(styles.get("cell_number"));


                            }
                            cell = dataRow.createCell(0);
                            cell.setCellValue(writeOffDate.substring(0, 4)+"/"+writeOffDate.substring(4, 6)+"/"+writeOffDate.substring(6));
                            cell.setCellStyle(styles.get("cell"));

                        } 
                        sheet.addMergedRegion(CellRangeAddress.valueOf(cellRangeAddress + ":$A$" + rownum));


                    }   

                }

            }

        }
    }
	 */
	/**
	 * Create a library of cell styles
	 */
	private static Map<String, CellStyle> createStyles(Workbook wb){
		Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
		CellStyle style;
		Font titleFont = wb.createFont();
		titleFont.setFontName("標楷體");
		titleFont.setFontHeightInPoints((short)24);
		style = wb.createCellStyle();
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		style.setFont(titleFont);
		styles.put("title", style);

		Font title2Font = wb.createFont();
		title2Font.setFontName("標楷體");
		//2011/05/13 jeff Gu  start   修正    報表excel檔修正 數值過長時欄位展開 問題
		title2Font.setFontHeightInPoints((short)12);
		style = wb.createCellStyle();
		style.setFont(title2Font);        
		style.setWrapText(false);//設定文字是否換行
		//2011/05/13 jeff Gu  end   修正    報表excel檔修正 數值過長時欄位展開 問題
		style.setAlignment(CellStyle.ALIGN_LEFT);
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		styles.put("title2", style);

		Font headerFont = wb.createFont();
		headerFont.setFontName("標楷體");
		headerFont.setFontHeightInPoints((short)12);
		style = wb.createCellStyle();
		style.setFont(headerFont);
		//2011/05/13 jeff Gu  start   修正    報表excel檔修正 數值過長時欄位展開 問題  
		style.setWrapText(false);//設定文字是否換行
		//2011/05/13 jeff Gu  end   修正    報表excel檔修正 數值過長時欄位展開 問題
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		style.setBorderRight(CellStyle.BORDER_THIN);
		style.setRightBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderLeft(CellStyle.BORDER_THIN);
		style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderTop(CellStyle.BORDER_THIN);
		style.setTopBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderBottom(CellStyle.BORDER_THIN);
		style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
		styles.put("header", style);

		Font cellFont = wb.createFont();
		cellFont.setFontName("標楷體");
		cellFont.setFontHeightInPoints((short)12);
		style = wb.createCellStyle();
		style.setFont(cellFont);
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		//2011/05/13 jeff Gu  start   修正    報表excel檔修正 數值過長時欄位展開 問題  
		style.setWrapText(false);//設定文字是否換行
		//2011/05/13 jeff Gu  end   修正    報表excel檔修正 數值過長時欄位展開 問題
		style.setBorderRight(CellStyle.BORDER_THIN);
		style.setRightBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderLeft(CellStyle.BORDER_THIN);
		style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderTop(CellStyle.BORDER_THIN);
		style.setTopBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderBottom(CellStyle.BORDER_THIN);
		style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
		styles.put("cell", style);

		style = wb.createCellStyle();
		style.setFont(cellFont);
		style.setAlignment(CellStyle.ALIGN_RIGHT);
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		style.setWrapText(false);//設定文字是否換行
		style.setBorderRight(CellStyle.BORDER_THIN);
		style.setRightBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderLeft(CellStyle.BORDER_THIN);
		style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderTop(CellStyle.BORDER_THIN);
		style.setTopBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderBottom(CellStyle.BORDER_THIN);
		style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
		styles.put("cell_ALIGN_RIGHT", style);

		style = wb.createCellStyle();
		Font cellNumberFont = wb.createFont();
		cellNumberFont.setFontName("Arial");
		cellNumberFont.setFontHeightInPoints((short)14);
		style.setFont(cellNumberFont);
		style.setAlignment(CellStyle.ALIGN_RIGHT);
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		//2011/05/13 jeff Gu  start   修正    報表excel檔修正 數值過長時欄位展開 問題  
		style.setWrapText(false);//設定文字是否換行
		//2011/05/13 jeff Gu  end   修正    報表excel檔修正 數值過長時欄位展開 問題
		style.setBorderRight(CellStyle.BORDER_THIN);
		style.setRightBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderLeft(CellStyle.BORDER_THIN);
		style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderTop(CellStyle.BORDER_THIN);
		style.setTopBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderBottom(CellStyle.BORDER_THIN);
		style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
		style.setDataFormat(wb.createDataFormat().getFormat("$#,##0"));
		styles.put("cell_number", style);

		style = wb.createCellStyle();
		Font cellDateFont = wb.createFont();
		cellDateFont.setFontName("Arial");
		cellDateFont.setFontHeightInPoints((short)12);
		style.setFont(cellDateFont);
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		//2011/05/13 jeff Gu  start   修正    報表excel檔修正 數值過長時欄位展開 問題  
		style.setWrapText(false);//設定文字是否換行
		//2011/05/13 jeff Gu  end   修正    報表excel檔修正 數值過長時欄位展開 問題
		style.setBorderRight(CellStyle.BORDER_THIN);
		style.setRightBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderLeft(CellStyle.BORDER_THIN);
		style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderTop(CellStyle.BORDER_THIN);
		style.setTopBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderBottom(CellStyle.BORDER_THIN);
		style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
		style.setDataFormat(wb.createDataFormat().getFormat("yyyy/MM/dd"));
		styles.put("cell_date", style);


		cellFont = wb.createFont();
		cellFont.setFontName("標楷體");
		cellFont.setFontHeightInPoints((short)18);
		cellFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
		style = wb.createCellStyle();
		style.setFont(cellFont);
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		//2011/05/13 jeff Gu  start   修正    報表excel檔修正 數值過長時欄位展開 問題  
		style.setWrapText(false);//設定文字是否換行
		//2011/05/13 jeff Gu  end   修正    報表excel檔修正 數值過長時欄位展開 問題
		style.setBorderRight(CellStyle.BORDER_THIN);
		style.setRightBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderLeft(CellStyle.BORDER_THIN);
		style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderTop(CellStyle.BORDER_THIN);
		style.setTopBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderBottom(CellStyle.BORDER_THIN);
		style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
		styles.put("cell_sub_total", style);

		style = wb.createCellStyle();
		cellNumberFont = wb.createFont();
		cellNumberFont.setFontName("Arial");
		cellNumberFont.setFontHeightInPoints((short)14);
		cellNumberFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
		style.setFont(cellNumberFont);
		style.setAlignment(CellStyle.ALIGN_RIGHT);
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		//2011/05/13 jeff Gu  start   修正    報表excel檔修正 數值過長時欄位展開 問題  
		style.setWrapText(false);//設定文字是否換行
		//2011/05/13 jeff Gu  end   修正    報表excel檔修正 數值過長時欄位展開 問題
		style.setBorderRight(CellStyle.BORDER_THIN);
		style.setRightBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderLeft(CellStyle.BORDER_THIN);
		style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderTop(CellStyle.BORDER_THIN);
		style.setTopBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderBottom(CellStyle.BORDER_THIN);
		style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
		style.setDataFormat(wb.createDataFormat().getFormat("$#,##0"));
		styles.put("cell_number_sub_total", style);




		cellFont = wb.createFont();
		cellFont.setFontName("標楷體");
		cellFont.setFontHeightInPoints((short)14);
		cellFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
		style = wb.createCellStyle();
		style.setFont(cellFont);
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		//2010/05/13 jeff Gu  start   修正    報表excel檔修正 數值過長時欄位展開 問題  
		style.setWrapText(false);//設定文字是否換行
		//2010/05/13 jeff Gu  end   修正    報表excel檔修正 數值過長時欄位展開 問題
		style.setBorderRight(CellStyle.BORDER_THIN);
		style.setRightBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderLeft(CellStyle.BORDER_THIN);
		style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderTop(CellStyle.BORDER_THIN);
		style.setTopBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderBottom(CellStyle.BORDER_THIN);
		style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
		styles.put("cell_total", style);

		style = wb.createCellStyle();
		cellNumberFont = wb.createFont();
		cellNumberFont.setFontName("Arial");
		cellNumberFont.setFontHeightInPoints((short)14);
		cellNumberFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
		style.setFont(cellNumberFont);
		style.setAlignment(CellStyle.ALIGN_RIGHT);
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		//2010/05/13 jeff Gu  start   修正    報表excel檔修正 數值過長時欄位展開 問題  
		style.setWrapText(false);//設定文字是否換行
		//2010/05/13 jeff Gu  end   修正    報表excel檔修正 數值過長時欄位展開 問題
		style.setBorderRight(CellStyle.BORDER_THIN);
		style.setRightBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderLeft(CellStyle.BORDER_THIN);
		style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderTop(CellStyle.BORDER_THIN);
		style.setTopBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderBottom(CellStyle.BORDER_THIN);
		style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
		style.setDataFormat(wb.createDataFormat().getFormat("$#,##0"));
		styles.put("cell_number_total", style);

		return styles;
	}

	/* (non-Javadoc)
	 * @see com.feib.soeasy.service.Soez5008Service#doExportStatisticsHtml(com.feib.soeasy.model.Group, java.lang.Integer, java.util.Date, java.util.Date)
	 */
	/*TODO JEFF 原本的畫面顯示excel 無法區分群組 需 @Deprecated*/
	@Deprecated
	@Override
	public String doExportStatisticsHtml(String[] channels, Date[] dateFroms, Date[] dateTos)
	{
		//Map<String , Object> dbData = queryStaticsByChainstoreData()
		StringBuffer html = new StringBuffer();
		//header row

		//總計數據
		Long totalCount = new Long(0);
		Long totalAmount = new Long(0);
		Long totalFee = new Long(0);
		Long totalRealAmount = new Long(0);

		StringBuffer codeHtml = new StringBuffer();



		for(int i=0;i<channels.length;i++)
		{
			String channel = channels[i];
			Date dateFrom = dateFroms[i];
			Date dateTo = dateTos[i];
			StringBuffer codeHtmlSub = new StringBuffer();

			//個別超商統計值
			Long channelCount = new Long(0);
			Long channelAmount = new Long(0);
			Long channelFee = new Long(0);
			Long channelRealAmount = new Long(0);

			if(channel != null && !"".equals(channel))
			{
				//找尋超商的Code,郵局部份會回傳一筆code為null的值
				/* jeff TODO 區分  群組*/
				List codes = this.queryCommissionCodes(channel, dateFrom, dateTo);
				if(codes == null)
				{
					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
					codeHtml.append("<tr>").append("\r\n");
					codeHtml.append("<td align='center'>").append("\r\n");
					codeHtml.append(dateFormat.format(dateFrom)).append("<br>～<br>").append(dateFormat.format(dateTo)).append("\r\n");
					codeHtml.append("</td>").append("\r\n");
					codeHtml.append("<td align='center'>").append("\r\n");
					codeHtml.append(codeTableDao.getCodeTable("CHANEL", channel).getCodeName()).append("\r\n");
					codeHtml.append("</td>").append("\r\n");
					codeHtml.append("<td colspan='6' align='center'>查無資料").append("\r\n");
					codeHtml.append("</td>").append("\r\n");
					codeHtml.append("<tr>").append("\r\n");
				}else
				{
					int smRowspan = 0;
					int cisCodeRowspan = 0;
					boolean first = true;
					StringBuffer bodyHtml = new StringBuffer();

					for(Iterator cis=codes.iterator();cis.hasNext();)
					{
						String code = (String)cis.next();

						// 取得超商(不含郵局)符合Code手續費
						long fee =0L;
						if (!channel.equals("H")) //非郵局
						{	
							CommissionCodeTable commissionCodeTable = commissionCodeTableDao.getCommissionCodeTable(code);
							if (commissionCodeTable!=null)       	            
								fee = commissionCodeTable.getGroupAmount();
						}

						//取得符合channel與commissionCode的每筆Feedback Log資料,組成統計值
						//List subSumData = this.queryStaticsByChainstoreData(channel, dateFrom, dateTo, commissionCode, null);        				
						List fbLogs = this.queryFeedbackLog(channel, code, dateFrom, dateTo);

						//個別Code統計值
						Long codeCount = new Long(0);
						Long codeAmount = new Long(0);
						Long codeFee = new Long(0);
						Long codeRealAmount = new Long(0);

						for(Iterator iter=fbLogs.iterator();iter.hasNext();)
						{
							codeCount++;
							Map fblog = (Map)iter.next();
							long txamt = ((BigDecimal)fblog.get("txamt")).longValue();  
							codeAmount += txamt;
							//取得郵局手續費
							if (channel.equals("H")) //郵局
							{
								Group gp = getGroupByVirtualAccount((String)fblog.get("userno"));
								if (gp == null)
									fee = 0;
								else
								{	
									groupDao.findByPk((long)1);
									if (txamt<=100) fee = gp.getPostLevel1();
									else if (txamt<=1000) fee = gp.getPostLevel2();
									else if (txamt>1000) fee = gp.getPostLevel3();
								}	
							}
							codeFee += fee;
							codeRealAmount += txamt - fee;
						}
						if(fbLogs != null && fbLogs.size() >0)
						{
							smRowspan = codes.size() + 1;
							cisCodeRowspan = 1;

							if(!first)
							{
								bodyHtml.append("<tr>").append("\r\n");
							}
							bodyHtml.append("<td align='center' rowspan='").append(String.valueOf(cisCodeRowspan)).append("'>").append("\r\n");
							if (code ==null) //郵局
							{	
								code = "N/A";
								bodyHtml.append("\r\n");
							}else	
								bodyHtml.append(code).append("\r\n");
							bodyHtml.append("</td>").append("\r\n");

							boolean view = true;

							bodyHtml.append("<td align='right'>").append("\r\n");
							bodyHtml.append(DateUtil.changeToComma(codeCount)).append("\r\n");
							bodyHtml.append("</td>").append("\r\n");
							bodyHtml.append("<td align='right'>").append("\r\n");
							bodyHtml.append(DateUtil.changeToComma(codeAmount)).append("\r\n");
							bodyHtml.append("</td>").append("\r\n");
							bodyHtml.append("<td align='right'>").append("\r\n");
							bodyHtml.append(DateUtil.changeToComma(codeFee)).append("\r\n");
							bodyHtml.append("</td>").append("\r\n");
							bodyHtml.append("<td align='right'>").append("\r\n");
							bodyHtml.append(DateUtil.changeToComma(codeRealAmount)).append("\r\n");
							bodyHtml.append("</td>").append("\r\n");

							if(view)
							{
								//
								SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
								String dateFormS = dateFormat.format(dateFrom);
								String dateFormE = dateFormat.format(dateTo);

								bodyHtml.append("<td align='right' rowspan='").append(String.valueOf(cisCodeRowspan)).append("'>").append("\r\n");
								bodyHtml.append("<div id='viewCommissionCodeImg-").append(channel).append(code).append(dateFormS).append(dateFormE)
								.append("'><a href=\"javascript: void(0)\" class='btnZoom'>查詢</a></div>");
								bodyHtml.append("</td>").append("\r\n");
								view = false;
							}

							bodyHtml.append("</tr>").append("\r\n");
							first = false;


							//加統計值
							channelCount += codeCount;
							channelAmount += codeAmount;
							channelFee += codeFee;
							channelRealAmount += codeRealAmount;

						}
					}
					//	    			if (channel.equals("H"))
					//	        		{
					//	        			smRowspan = smRowspan + 1;
					//	        		}
					//smRowspan = smRowspan + 1;
					bodyHtml.append("<tr>").append("\r\n");
					bodyHtml.append("<td align='right' >").append("\r\n");
					bodyHtml.append("統計").append("\r\n");
					bodyHtml.append("</td>").append("\r\n");
					/* 效能提升  超商／郵局傳輸統計查詢  總計記數 */
					bodyHtml.append("<td align='right' >").append("\r\n");
					bodyHtml.append(channelCount).append("\r\n");
					bodyHtml.append("</td>").append("\r\n");
					bodyHtml.append("<td align='right'>").append("\r\n");
					bodyHtml.append(DateUtil.changeToComma(channelAmount)).append("\r\n");
					bodyHtml.append("</td>").append("\r\n");
					bodyHtml.append("<td align='right'>").append("\r\n");
					bodyHtml.append(DateUtil.changeToComma(channelFee)).append("\r\n");
					bodyHtml.append("</td>").append("\r\n");
					bodyHtml.append("<td align='right'>").append("\r\n");
					bodyHtml.append(DateUtil.changeToComma(channelRealAmount)).append("\r\n");
					bodyHtml.append("</td>").append("\r\n");
					bodyHtml.append("<td align='right'></td>").append("\r\n");
					bodyHtml.append("</tr>").append("\r\n");

					//=======================================================================
					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
					codeHtmlSub.append("<tr>").append("\r\n");
					codeHtmlSub.append("<td align='center' rowspan='").append(String.valueOf(smRowspan)).append("'>").append("\r\n");
					codeHtmlSub.append(dateFormat.format(dateFrom)).append("<br>～<br>").append(dateFormat.format(dateTo)).append("\r\n");
					codeHtmlSub.append("</td>").append("\r\n");
					codeHtmlSub.append("<td align='center' rowspan='").append(String.valueOf(smRowspan)).append("'>").append("\r\n");
					codeHtmlSub.append(codeTableDao.getCodeTable("CHANEL", channel).getCodeName()).append("\r\n");

					codeHtmlSub.append("</td>").append("\r\n");

					codeHtmlSub.append(bodyHtml.toString()).append("\r\n");
					codeHtml.append(codeHtmlSub.toString());


					//總合計
					totalCount += channelCount;
					totalAmount += channelAmount;
					totalFee += channelFee;
					totalRealAmount += channelRealAmount;
				}		
			}
		}

		//------------------------------------------------------------------------------------------------------------


		//串欄位表頭
		String[] titles = {
				"傳輸日期","超商","CODE" ,"代收筆數", "代收金額" , "代收手續費" ,"實撥金額","明細"};

		html.append("<table id=\"listTable\">").append("\r\n");
		html.append("<thead><tr>").append("\r\n");

		for (int j = 0; j < titles.length; j++) {
			html.append("<th>").append(titles[j]).append("</th>").append("\r\n");
		}

		html.append("</tr></thead>").append("\r\n");
		html.append("<tbody>").append("\r\n");


		if(codeHtml.length() != 0)
		{
			html.append(codeHtml.toString()).append("\r\n");

			html.append("<tr>").append("\r\n");
			html.append("<td align='center' colspan='2'>").append("\r\n");
			html.append("總計").append("\r\n");
			html.append("</td>").append("\r\n");	      
			html.append("<td align='right'>").append("\r\n");
			html.append("超商／郵局合計").append("\r\n");
			html.append("</td>").append("\r\n");
			/* 效能提升  超商／郵局傳輸統計查詢  總計記數 */
			html.append("<td align='right'>").append("\r\n");
			html.append(totalCount).append("\r\n");
			html.append("</td>").append("\r\n");
			html.append("<td align='right'>").append("\r\n");
			html.append(DateUtil.changeToComma(totalAmount)).append("\r\n");
			html.append("</td>").append("\r\n");
			html.append("<td align='right'>").append("\r\n");
			html.append(DateUtil.changeToComma(totalFee)).append("\r\n");
			html.append("</td>").append("\r\n");
			html.append("<td align='right'>").append("\r\n");
			html.append(DateUtil.changeToComma(totalRealAmount)).append("\r\n");
			html.append("</td>").append("\r\n");
			html.append("</tr>").append("\r\n");

			// 下載按鈕
			html.append("<tr>").append("\r\n");
			html.append("<td colspan=\"8\" align=\"center\">")
			.append("<input type=\"button\" id=\"doDownloadExcelFileBtn\" value=\"下載(Excel)\" onclick=\"javascript:doDownloadExcelFileAction();\" />")
			.append(" <input type=\"button\" id=\"printBtn2\" value=\"列印\"  onclick=\"javascript:divPrint('queryResultDiv');\" />") 
			.append("</td>").append("\r\n");
			html.append("</tr>").append("\r\n");

			html.append("</tbody></table>").append("\r\n");

			html.append("<script type=\"text/javascript\">").append("\r\n");
			html.append("<!--").append("\r\n");
			html.append("$(document).ready(function() {").append("\r\n");
			html.append("$(\"[id^='viewCommissionCodeImg-']\").click(function() {").append("\r\n");
			html.append("var uid = this.id.substring(22);").append("\r\n");
			html.append("doQueryDetailAction(uid); ").append("\r\n");
			html.append("});").append("\r\n");
			html.append("});").append("\r\n");
			html.append("//-->").append("\r\n");
			html.append("</script>").append("\r\n");
			html.append("");	
		}else
		{
			html.append("<tr>").append("\r\n");
			html.append("<td colspan=\"8\" align=\"center\">")
			.append("無超商資料")
			.append("</td>").append("\r\n");
			html.append("</tr>").append("\r\n");
		}


		return html.toString();
	}

	/**
	 * @param html
	 * @param dbData
	 */
	/*    private void writeHtmlData(StringBuffer html, Map<String, Map<String, List<Map<String, Object>>>> dbData) {
        //dbData 以時間做key的集合

        if (null != dbData && 0 != dbData.size())
        {
            boolean first = true;
            boolean innerfirst = true;
            //日期集合
            Set<String> dbDataKeys1=dbData.keySet();

            //通路
            String dbDataKeys[] = new String[]{WriteOffPayment.CHANNEL_7_11, WriteOffPayment.CHANNEL_FAMILY_MART
                            , WriteOffPayment.CHANNEL_OK_MART,WriteOffPayment.CHANNEL_HILIFE };
            //
            for (String key1 :dbDataKeys1){    
                int count =0;
                for (String key :dbDataKeys){ 
                    List<Map<String, Object>>  channelDatas = dbData.get(key1).get(key);
                    if(null !=channelDatas && 0 != channelDatas.size())  {

                        count+= channelDatas.size();
                    }

                }

                for (String key :dbDataKeys){                    
                    // List<Map<String, Object>> channelDatas=new  ArrayList<Map<String, Object>> ();
                    List<Map<String, Object>>  channelDatas = dbData.get(key1).get(key);


                    String writeOffDate = key1;



                    if(null !=channelDatas && 0 != channelDatas.size())  {


                        html.append("<tr>").append("\r\n");
                        if (first)
                        {
                            html.append("<td rowspan=\"").append(count).append("\">")
                            .append(writeOffDate.substring(0, 4)).append("/").append(writeOffDate.substring(4, 6)).append("/").append(writeOffDate.substring(6))
                            .append("</td>");
                            first = false;
                        }  
                        for(Map<String, Object> channelData : channelDatas)
                        {

                            String channelName = (String)channelData.get("CHANNEL_NAME");
                            String commissionCode = (String)channelData.get("COMMISSION_CODE");
                            String commissionCodeName = (String)channelData.get("COMMISSION_CODE_NAME");
                            Long recordCount = (Long)channelData.get("RECORD_COUNT");
                            Long amount = (Long)channelData.get("AMOUNT");
                            Long commissionAmount = (Long)channelData.get("COMMISSION_AMOUNT");
                            Long realAmount = (Long)channelData.get("REAL_AMOUNT");




                            if (innerfirst)
                            {
                                html.append("<td rowspan=\"").append(channelDatas.size()).append("\">").append(channelName).append("</td>");
                                innerfirst = false;
                            }  

                            // commissionCodewriteOffDate
                            //      html.append("<td>").append(channelName).append("</td>").append("\r\n");
                            html.append("<td>").append(commissionCode).append("</td>").append("\r\n");
                            // 代收類別
                            html.append("<td>").append(commissionCodeName).append("</td>").append("\r\n");
                            if(commissionCode.equals("小計")){
                                html.append("<td align=\"right\">").append("").append("</td>").append("\r\n");  
                            }else{   // 代收手續費小計}
                                html.append("<td align=\"right\">").append(numberFormat.format(commissionAmount)).append("</td>").append("\r\n");  
                            }

                            // 代收筆數小計
                            html.append("<td align=\"right\">").append(numberFormat.format(recordCount)).append("</td>").append("\r\n");
                            // 代收金額小計
                            html.append("<td align=\"right\">").append(numberFormat.format(amount)).append("</td>").append("\r\n");

                            // 實際入帳金額小計
                            html.append("<td align=\"right\">").append(numberFormat.format(realAmount)).append("</td>").append("\r\n");

                            html.append("</tr>").append("\r\n"); 
                        } 
                        innerfirst = true;

                    }

                }
                first = true;
            }     
        }
    }
	 */

	/*TODO JEFF 原本的畫面明細顯示 無法區分群組 需 @Deprecated*/
	@Override
	public List queryFeedbackLogByChannelCommission(String channel, String commissionCode, Date qryDateFrom, Date qryDateTo ) 
	{
		if (null != qryDateFrom)
		{
			// 將時分秒設定在00:00:00
			qryDateFrom = DateUtil.getBeginOfDateTime(qryDateFrom);
		}

		if (null != qryDateTo)
		{
			// 將時分秒設定在23:59:59
			qryDateTo = DateUtil.getEndOfDateTime(qryDateTo);
		}

		List fbLogs = soez5008Dao.queryFeedbackLog(channel, commissionCode, qryDateFrom, qryDateTo);
		if(fbLogs == null || fbLogs.size() == 0)
			return null;

		// 取得超商(不含郵局)符合Code手續費
		long fee =0L;
		if (!channel.equals("H")) //非郵局
		{	
			CommissionCodeTable commissionCodeTable = commissionCodeTableDao.getCommissionCodeTable(commissionCode);
			if (commissionCodeTable!=null)       	            
				fee = commissionCodeTable.getGroupAmount();
		}


		/* 效能提升  超商／郵局傳輸統計查詢  總計記數 */
		Long totalCount = new Long(0);
		Long totalAmount = new Long(0);
		Long totalFee = new Long(0);

		List results = new ArrayList();
		for(Iterator iter=fbLogs.iterator();iter.hasNext();)
		{
			Map fblog = (Map)iter.next();
			//
			//            Object[] obj = (Object[])list.get(i);
			//    		Group group = new Group();
			//    		Payment payment = new Payment();
			//    		WriteOffPayment writeOffPayment = new WriteOffPayment();
			//    		
			//    		group.setGroupNo((String)obj[0]);
			//    		group.setGroupName((String)obj[1]);
			//    		payment.setVirtualAccount((String)obj[2]);
			//    		payment.setPayerName((String)obj[3]);
			//    		payment.setPayerId((String)obj[4]);
			//    		writeOffPayment.setTxDate((Date)obj[5]);
			//    		writeOffPayment.setWriteOffDate((Date)obj[6]);
			//    		writeOffPayment.setAmount(new Long(((BigDecimal)obj[7]).longValue()));
			//    		
			//    		
			//    		payment.setGroup(group);
			//    		payment.setWriteOffPayment(writeOffPayment);

			//個別Code統計值
			Long codeCount = new Long(0);
			Long codeAmount = new Long(0);
			Long codeFee = new Long(0);

			/*超商欄位*/
			String  codeName =  codeTableDao.getCodeTable("CHANEL", channel).getCodeName();
			fblog.put("codeName", codeName);
			/*代號*/
			fblog.put("commissionCode", commissionCode);

			String userno = (String)fblog.get("userno");

			//取得郵局繳費日期
			if (channel.equals("H")) //郵局
			{
				Payment payment = paymentDao.queryPaymentByVirtualAccount(userno,true);
				if (payment==null) payment = paymentDao.queryPaymentByVirtualAccount(userno,false);
				if (payment!=null) fblog.put("dueday", payment.getPayDue()); 
			}		



			//取得帳單業者
			Group gp = getGroupByVirtualAccount(userno);
			if (gp == null)
				fblog.put("gpname", "");
			else
			{
				fblog.put("gpname", gp.getGroupName());
			}

			//計算手續費
			long txamt = ((BigDecimal)fblog.get("txamt")).longValue();
			if (channel.equals("H")) //郵局
			{
				if (txamt<=100) fee = gp.getPostLevel1();
				else if (txamt<=1000) fee = gp.getPostLevel2();
				else if (txamt>1000) fee = gp.getPostLevel3();
			}
			fblog.put("fee", fee);

			//個別Code統計值
			codeCount++;
			codeAmount += txamt;
			codeFee +=fee;
			//加統計值
			totalCount += codeCount;
			totalAmount += codeAmount;
			totalFee += codeFee;

			fblog.put("totalCount", totalCount);
			fblog.put("totalAmount", totalAmount);
			fblog.put("totalFee", totalFee);

			results.add(fblog);





			/*    		if(i < (list.size()-1))
    		{
    			Object[] obj2 = (Object[])list.get(i+1);
    			String groupNo2 = (String)obj2[0];
    			if(!groupNo2.equals(group.getGroupNo()))
    			{
    				group = groupDao.findByGroupNo(group.getGroupNo());
    				List feedbackLogs = soez5008Dao.queryFeedBackLog(group, qryDateFrom, qryDateTo, channel, commissionCode);
    				logger.debug("FeedBackLog 1 size:{}", feedbackLogs.size());

    	    		for(Iterator f=feedbackLogs.iterator();f.hasNext();)
    		    	{
	    	    		Map feedBackMap = (Map)f.next();
	    	    		CommissionCodeTable commissionCodeTable = null;
	    	    		String commission = ((String)feedBackMap.get("BARCDOE1")).substring(6,9);
	    	            Long txamt = new Long(String.valueOf(feedBackMap.get("TXAMT")));
	    	            String aday = (String)feedBackMap.get("ADAY");
	    	            String wday = (String)feedBackMap.get("FBTIME");
	    	            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

	    	            Payment payment2 = new Payment();
	    	    		WriteOffPayment writeOffPayment2 = new WriteOffPayment();
	    	    		try {
	    	    			writeOffPayment2.setTxDate(dateFormat.parse(aday));
	    	    			writeOffPayment2.setWriteOffDate(dateFormat.parse(wday));
	    	    			writeOffPayment2.setAmount(txamt);
	    	    			payment2.setGroup(group);
	    	    			payment2.setVirtualAccount("銷帳失敗");
	    	        		payment2.setWriteOffPayment(writeOffPayment2);
	    	        		results.add(payment2);
						} catch (Exception e) {
							// TODO: handle exception
						}
    		    	}
    			}    			    			
    		}

			if(i == (list.size()-1))
			{
    			Object[] obj2 = (Object[])list.get(i);
    			String groupNo2 = (String)obj2[0];

				group = groupDao.findByGroupNo(group.getGroupNo());
				List feedbackLogs = soez5008Dao.queryFeedBackLog(group, qryDateFrom, qryDateTo, channel, commissionCode);
				logger.debug("FeedBackLog 2 size:{}", feedbackLogs.size());
				for(Iterator f=feedbackLogs.iterator();f.hasNext();)
		    	{
    	    		Map feedBackMap = (Map)f.next();
    	    		CommissionCodeTable commissionCodeTable = null;
    	    		String commission = ((String)feedBackMap.get("BARCDOE1")).substring(6,9);
    	            Long txamt = new Long(String.valueOf(feedBackMap.get("TXAMT")));
    	            String aday = (String)feedBackMap.get("ADAY");
    	            String wday = (String)feedBackMap.get("FBTIME");
    	            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

    	            Payment payment2 = new Payment();
    	    		WriteOffPayment writeOffPayment2 = new WriteOffPayment();
    	    		try {
    	    			writeOffPayment2.setTxDate(dateFormat.parse(aday));
    	    			writeOffPayment2.setWriteOffDate(dateFormat.parse(wday));
    	    			writeOffPayment2.setAmount(txamt);
    	    			payment2.setGroup(group);
    	    			payment2.setVirtualAccount("銷帳失敗");
    	        		payment2.setWriteOffPayment(writeOffPayment2);
    	        		results.add(payment2);
					} catch (Exception e) {
						// TODO: handle exception
					}

		    	}

			}
			 */

		}




		return results;
	}

	//取得帳單業者 
	private Group getGroupByVirtualAccount(String vaccount)
	{
		String virtual_account_4 = vaccount.substring(0,4); //先比對4碼
		String virtual_account_3 = vaccount.substring(0,3); //4碼找不到再比對3碼
		RealAccount entity = new RealAccount();
		entity.setVirtualAccountNo(virtual_account_4);
		RealAccount account = realAccountDao.queryByVirtualAccount(entity);
		if (account == null) //4碼找不到再比對3碼
		{
			entity.setVirtualAccountNo(virtual_account_3);
			account = realAccountDao.queryByVirtualAccount(entity);
		}
		if (account == null) //3碼4碼皆找不到
			return null;
		else
		{
			return account.getGroup();
		}
	}


	/*TODO  jeff 新的的取得單種代號明細FeedbackLog  */
	@Override
	public PaginatedList<Map<String, Object>> queryGroupFeedbackLogByChannelCommission(
			Group group, String channel, String commissionCode,
			Date qryDateFrom, Date qryDateTo,PaginatedList<Map<String, Object>> paginationConfig) {
		if (null != qryDateFrom)
		{
			// 將時分秒設定在00:00:00
			qryDateFrom = DateUtil.getBeginOfDateTime(qryDateFrom);
		}

		if (null != qryDateTo)
		{
			// 將時分秒設定在23:59:59
			qryDateTo = DateUtil.getEndOfDateTime(qryDateTo);
		}

		if(null==group)
			group=new Group();

		if (!UserUtil.isBankGroup())
		{
			group=UserUtil.getUserGroup();
		}
		Map<String, String> channelCode=new HashMap<String, String>();

		channelCode.put( "7111111","D");
		channelCode.put("TFM","E" );
		channelCode.put( "HILIFE","F");
		channelCode.put( "OKCVS","G");
		channelCode.put("POST","H");

		PaginatedList<Map<String, Object>> fbLogs = soez5008Dao.queryGroupFeedbackLog(group, channel, commissionCode, qryDateFrom, qryDateTo, paginationConfig);


		if(fbLogs.getPaginatedList()== null || fbLogs.getPaginatedList().size() == 0)
			return null;

		// 取得超商(不含郵局)符合Code手續費
		long fee =0L;
		if (!channel.equals("H")) //非郵局
		{	
			CommissionCodeTable commissionCodeTable = commissionCodeTableDao.getCommissionCodeTable(commissionCode);
			if (commissionCodeTable!=null)       	            
				fee = commissionCodeTable.getGroupAmount();
		}


		/* 效能提升  超商／郵局傳輸統計查詢  總計記數 */
		Long totalCount = new Long(0);
		Long totalAmount = new Long(0);
		Long totalFee = new Long(0);
		/* 設定複製用PaginatedList 再對資料作處理 不然 foreach的狀況下不能對來源檔案作操作  */
		PaginatedList<Map<String, Object>> results = new PaginatedList<Map<String, Object>>();				
		results.setFullListSize(fbLogs.getFullListSize());
		results.setPageSize(fbLogs.getPageSize());
        results.setPageNumber(fbLogs.getPageNumber());
        results.setSortCriterion(fbLogs.getSortCriterion());
        results.setSortDirection(fbLogs.getSortDirection());
        
		List<Map<String, Object>> temp = new ArrayList<Map<String, Object>>();
		for(Map<String, Object> fblog:fbLogs.getPaginatedList())
		{	
			//個別Code統計值
			Long codeCount = new Long(0);
			Long codeAmount = new Long(0);
			Long codeFee = new Long(0);

			/*超商欄位*/
			String  codeName =  codeTableDao.getCodeTable("CHANEL", channel).getCodeName();
			fblog.put("codeName", codeName);
			/*代號*/
			fblog.put("commissionCode", commissionCode);

			String userno = (String)fblog.get("userno");

			//取得郵局繳費日期
			if (channel.equals("H")) //郵局
			{
				Payment payment = paymentDao.queryPaymentByVirtualAccount(userno,true);
				if (payment==null) payment = paymentDao.queryPaymentByVirtualAccount(userno,false);
				if (payment!=null) fblog.put("dueday", payment.getPayDue()); 
			}		

			//取得帳單業者
			Group gp = getGroupByVirtualAccount(userno);
			logger.debug("gp {}",gp);
			if (gp == null)
				fblog.put("gpname", "");
			else
			{
				fblog.put("gpname", gp.getGroupName());
			}

			//計算手續費
			long txamt = ((BigDecimal)fblog.get("txamt")).longValue();
			if (channel.equals("H")) //郵局
			{
				if (txamt<=100) fee = gp.getPostLevel1();
				else if (txamt<=1000) fee = gp.getPostLevel2();
				else if (txamt>1000) fee = gp.getPostLevel3();
			}
			fblog.put("fee", fee);

			//個別Code統計值
			codeCount++;
			codeAmount += txamt;
			codeFee +=fee;
			//加統計值
			totalCount += codeCount;
			totalAmount += codeAmount;
			totalFee += codeFee;

			fblog.put("totalCount", totalCount);
			fblog.put("totalAmount", totalAmount);
			fblog.put("totalFee", totalFee);

			/*計算總計*/
			temp.add(fblog);

		}

		results.setPaginatedList(temp);
		/* 清除資源*/
		fbLogs.getPaginatedList().clear();
		fbLogs=null;

		return results;
	}

	/**TODO  jeff 新的查詢畫面
	 * 取得FeedbackLog 資料 需區分群組
	 * */
	public List<Map<String, Object>> queryGroupFeedbackLog(Group group,String channel, String code, Date qryDateFrom, Date qryDateTo)
	{
		if (null != qryDateFrom)
		{
			// 將時分秒設定在00:00:00
			qryDateFrom = DateUtil.getBeginOfDateTime(qryDateFrom);
		}

		if (null != qryDateTo)
		{
			// 將時分秒設定在23:59:59
			qryDateTo = DateUtil.getEndOfDateTime(qryDateTo);
		}
		if(null==group)
			group=new Group();

		if (!UserUtil.isBankGroup())
		{
			group=UserUtil.getUserGroup();
		}


		if(channel != null)
		{
			/*TODO 改成明細*/
			List<Map<String, Object>> fbLogList = soez5008Dao.queryGroupFeedbackLog(group,channel, code, qryDateFrom, qryDateTo);
			if(fbLogList != null && fbLogList.size() != 0)
				return fbLogList;

		}
		return null;
	}
	/*TODO  jeff 新的的取得COMMISSCODES */
	public List<String> queryGroupCommissionCodes(Group group,String channel, Date qryDateFrom, Date qryDateTo)
	{
		if (null != qryDateFrom)
		{
			// 將時分秒設定在00:00:00
			qryDateFrom = DateUtil.getBeginOfDateTime(qryDateFrom);
		}

		if (null != qryDateTo)
		{
			// 將時分秒設定在23:59:59
			qryDateTo = DateUtil.getEndOfDateTime(qryDateTo);
		}

		if(null==group)
			group=new Group();

		if (!UserUtil.isBankGroup())
		{
			group=UserUtil.getUserGroup();
		}

		if(channel != null)
		{
			List<String> commissionCodes = soez5008Dao.queryGroupCommissionCode(group, channel, qryDateFrom, qryDateTo);
			if(commissionCodes != null && commissionCodes.size() != 0)
			{				
				return commissionCodes;
			}
		}
		return null;
	}

	@Override
	/**
	 * 根據通路 代碼 跟日期 取得  顯示畫面 (可分群組)
	 * @author Jeff
	 */
	public String doExportGroupStatisticsHtml(Group group, String[] channels,
			Date[] dateFroms, Date[] dateTos) {
		StringBuffer html = new StringBuffer();

		//總計數據
		Long totalCount = new Long(0);
		Long totalAmount = new Long(0);
		Long totalFee = new Long(0);
		Long totalRealAmount = new Long(0);

		StringBuffer codeHtml = new StringBuffer();

		if(null==group)
			group=new Group();

		if (!UserUtil.isBankGroup())
		{
			group=UserUtil.getUserGroup();
		}
		/* 依通路分類 */
		for(int i=0;i<channels.length;i++)
		{
			String channel = channels[i];
			Date dateFrom = dateFroms[i];
			Date dateTo = dateTos[i];
			StringBuffer codeHtmlSub = new StringBuffer();

			//個別超商統計值
			Long channelCount = new Long(0);
			Long channelAmount = new Long(0);
			Long channelFee = new Long(0);
			Long channelRealAmount = new Long(0);

			if(channel != null && !"".equals(channel))
			{
				//找尋超商的Code,郵局部份會回傳一筆code為null的值
				List<String> codes = this.queryGroupCommissionCodes(group, channel, dateFrom, dateTo);
				if(codes == null)
				{
					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
					codeHtml.append("<tr>").append("\r\n");
					codeHtml.append("<td align='center'>").append("\r\n");
					codeHtml.append(dateFormat.format(dateFrom)).append("<br>～<br>").append(dateFormat.format(dateTo)).append("\r\n");
					codeHtml.append("</td>").append("\r\n");
					codeHtml.append("<td align='center'>").append("\r\n");
					codeHtml.append(codeTableDao.getCodeTable("CHANEL", channel).getCodeName()).append("\r\n");
					codeHtml.append("</td>").append("\r\n");
					codeHtml.append("<td colspan='6' align='center'>查無資料").append("\r\n");
					codeHtml.append("</td>").append("\r\n");
					codeHtml.append("<tr>").append("\r\n");
				}else
				{
					int smRowspan = 0;
					int cisCodeRowspan = 0;
					boolean first = true;
					StringBuffer bodyHtml = new StringBuffer();

					for(String code:codes)
					{

						// 取得超商(不含郵局)符合Code手續費
						long fee =0L;
						if (!channel.equals("H")) //非郵局
						{	
							CommissionCodeTable commissionCodeTable = commissionCodeTableDao.getCommissionCodeTable(code);
							if (commissionCodeTable!=null)       	            
								fee = commissionCodeTable.getGroupAmount();
						}

						//取得符合channel與commissionCode的每筆Feedback Log資料,組成統計值
						List<Map<String, Object>> fbLogs = this.queryGroupFeedbackLog(group, channel, code, dateFrom, dateTo);

						//個別Code統計值
						Long codeCount = new Long(0);
						Long codeAmount = new Long(0);
						Long codeFee = new Long(0);
						Long codeRealAmount = new Long(0);

						for(Map<String, Object> fblog:fbLogs)
						{
							codeCount++;
							long txamt = ((BigDecimal)fblog.get("txamt")).longValue();  
							codeAmount += txamt;
							//取得郵局手續費
							if (channel.equals("H")) //郵局
							{
								Group gp = getGroupByVirtualAccount((String)fblog.get("userno"));
								if (gp == null)
									fee = 0;
								else
								{	
									groupDao.findByPk((long)1);
									if (txamt<=100) fee = gp.getPostLevel1();
									else if (txamt<=1000) fee = gp.getPostLevel2();
									else if (txamt>1000) fee = gp.getPostLevel3();
								}	
							}
							codeFee += fee;
							codeRealAmount += txamt - fee;
						}
						if(fbLogs != null && fbLogs.size() >0)
						{
							smRowspan = codes.size() + 1;
							cisCodeRowspan = 1;

							if(!first)
							{
								bodyHtml.append("<tr>").append("\r\n");
							}
							bodyHtml.append("<td align='center' rowspan='").append(String.valueOf(cisCodeRowspan)).append("'>").append("\r\n");
							if (code ==null) //郵局
							{	
								code = "N/A";
								bodyHtml.append("\r\n");
							}else	
								bodyHtml.append(code).append("\r\n");
							bodyHtml.append("</td>").append("\r\n");

							boolean view = true;

							bodyHtml.append("<td align='right'>").append("\r\n");
							bodyHtml.append(DateUtil.changeToComma(codeCount)).append("\r\n");
							bodyHtml.append("</td>").append("\r\n");
							bodyHtml.append("<td align='right'>").append("\r\n");
							bodyHtml.append(DateUtil.changeToComma(codeAmount)).append("\r\n");
							bodyHtml.append("</td>").append("\r\n");
							bodyHtml.append("<td align='right'>").append("\r\n");
							bodyHtml.append(DateUtil.changeToComma(codeFee)).append("\r\n");
							bodyHtml.append("</td>").append("\r\n");
							bodyHtml.append("<td align='right'>").append("\r\n");
							bodyHtml.append(DateUtil.changeToComma(codeRealAmount)).append("\r\n");
							bodyHtml.append("</td>").append("\r\n");

							if(view)
							{
								//
								SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
								String dateFormS = dateFormat.format(dateFrom);
								String dateFormE = dateFormat.format(dateTo);

								bodyHtml.append("<td align='right' rowspan='").append(String.valueOf(cisCodeRowspan)).append("'>").append("\r\n");
								bodyHtml.append("<div id='viewCommissionCodeImg-").append(channel).append(code).append(dateFormS).append(dateFormE)
								.append("'><a href=\"javascript: void(0)\" class='btnZoom'>查詢</a></div>");
								bodyHtml.append("</td>").append("\r\n");
								view = false;
							}

							bodyHtml.append("</tr>").append("\r\n");
							first = false;


							//加統計值
							channelCount += codeCount;
							channelAmount += codeAmount;
							channelFee += codeFee;
							channelRealAmount += codeRealAmount;

						}
					}

					bodyHtml.append("<tr>").append("\r\n");
					bodyHtml.append("<td align='right' >").append("\r\n");
					bodyHtml.append("統計").append("\r\n");
					bodyHtml.append("</td>").append("\r\n");
					/* 效能提升  超商／郵局傳輸統計查詢  總計記數 */
					bodyHtml.append("<td align='right' >").append("\r\n");
					bodyHtml.append(channelCount).append("\r\n");
					bodyHtml.append("</td>").append("\r\n");
					bodyHtml.append("<td align='right'>").append("\r\n");
					bodyHtml.append(DateUtil.changeToComma(channelAmount)).append("\r\n");
					bodyHtml.append("</td>").append("\r\n");
					bodyHtml.append("<td align='right'>").append("\r\n");
					bodyHtml.append(DateUtil.changeToComma(channelFee)).append("\r\n");
					bodyHtml.append("</td>").append("\r\n");
					bodyHtml.append("<td align='right'>").append("\r\n");
					bodyHtml.append(DateUtil.changeToComma(channelRealAmount)).append("\r\n");
					bodyHtml.append("</td>").append("\r\n");
					/* 單通路明細 */
					if(channelCount>0){							
						SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
						String dateFormS = dateFormat.format(dateFrom);
						String dateFormE = dateFormat.format(dateTo);						
						bodyHtml.append("<td align='right' >").append("\r\n");
						bodyHtml.append("<div id='viewChannel-")
						.append(channel).append(dateFormS).append(dateFormE)						
						.append("'><a href=\"javascript: void(0)\" class='btnZoom'>查詢</a></div>");
						bodyHtml.append("</td>").append("\r\n");
					}
					
					bodyHtml.append("</tr>").append("\r\n");

					//=======================================================================
					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
					codeHtmlSub.append("<tr>").append("\r\n");
					codeHtmlSub.append("<td align='center' rowspan='").append(String.valueOf(smRowspan)).append("'>").append("\r\n");
					codeHtmlSub.append(dateFormat.format(dateFrom)).append("<br>～<br>").append(dateFormat.format(dateTo)).append("\r\n");
					codeHtmlSub.append("</td>").append("\r\n");
					codeHtmlSub.append("<td align='center' rowspan='").append(String.valueOf(smRowspan)).append("'>").append("\r\n");
					codeHtmlSub.append(codeTableDao.getCodeTable("CHANEL", channel).getCodeName()).append("\r\n");

					codeHtmlSub.append("</td>").append("\r\n");

					codeHtmlSub.append(bodyHtml.toString()).append("\r\n");
					codeHtml.append(codeHtmlSub.toString());


					//總合計
					totalCount += channelCount;
					totalAmount += channelAmount;
					totalFee += channelFee;
					totalRealAmount += channelRealAmount;
				}		
			}
		}

		//------------------------------------------------------------------------------------------------------------


		//串欄位表頭
		String[] titles = {
				"傳輸日期","超商","CODE" ,"代收筆數", "代收金額" , "代收手續費" ,"實撥金額","明細"};

		html.append("<table id=\"listTable\">").append("\r\n");
		html.append("<thead><tr>").append("\r\n");

		for (int j = 0; j < titles.length; j++) {
			html.append("<th>").append(titles[j]).append("</th>").append("\r\n");
		}

		html.append("</tr></thead>").append("\r\n");
		html.append("<tbody>").append("\r\n");


		if(codeHtml.length() != 0)
		{
			html.append(codeHtml.toString()).append("\r\n");

			html.append("<tr>").append("\r\n");
			html.append("<td align='center' colspan='2'>").append("\r\n");
			html.append("總計").append("\r\n");
			html.append("</td>").append("\r\n");	      
			html.append("<td align='right'>").append("\r\n");
			html.append("超商／郵局合計").append("\r\n");
			html.append("</td>").append("\r\n");
			/* 效能提升  超商／郵局傳輸統計查詢  總計記數 */
			html.append("<td align='right'>").append("\r\n");
			html.append(totalCount).append("\r\n");
			html.append("</td>").append("\r\n");
			html.append("<td align='right'>").append("\r\n");
			html.append(DateUtil.changeToComma(totalAmount)).append("\r\n");
			html.append("</td>").append("\r\n");
			html.append("<td align='right'>").append("\r\n");
			html.append(DateUtil.changeToComma(totalFee)).append("\r\n");
			html.append("</td>").append("\r\n");
			html.append("<td align='right'>").append("\r\n");
			html.append(DateUtil.changeToComma(totalRealAmount)).append("\r\n");
			html.append("</td>").append("\r\n");
			/*TODO 0755 總明細  有總計數目再顯示*/
			if(totalCount>0){	
				html.append("<td align='right' >").append("\r\n");
				html.append("<div id='viewTotal-1")
				.append("'><a href=\"javascript: void(0)\" class='btnZoom'>查詢</a></div>");
				html.append("</td>").append("\r\n");
			}
			html.append("</tr>").append("\r\n");
			// 下載按鈕
			html.append("<tr>").append("\r\n");
			html.append("<td colspan=\"8\" align=\"center\">")
			.append("<input type=\"button\" id=\"doDownloadExcelFileBtn\" value=\"下載(Excel)\" onclick=\"javascript:doDownloadExcelFileAction();\" />")
			.append(" <input type=\"button\" id=\"printBtn2\" value=\"列印\"  onclick=\"javascript:divPrint('queryResultDiv');\" />") 
			.append("</td>").append("\r\n");
			html.append("</tr>").append("\r\n");

			html.append("</tbody></table>").append("\r\n");

			html.append("<script type=\"text/javascript\">").append("\r\n");
			html.append("<!--").append("\r\n");
			html.append("$(document).ready(function() {").append("\r\n");
			html.append("$(\"[id^='viewCommissionCodeImg-']\").click(function() {").append("\r\n");
			html.append("var uid = this.id.substring(22);").append("\r\n");
			html.append("doQueryDetailAction(uid); ").append("\r\n");
			html.append("});").append("\r\n");
			html.append("$(\"[id^='viewTotal-']\").click(function() {").append("\r\n");
			html.append("var uid = this.id.substring(10);").append("\r\n");
			html.append("doQueryTotalAction(uid); ").append("\r\n");
			html.append("});").append("\r\n");
			html.append("$(\"[id^='viewChannel-']\").click(function() {").append("\r\n");
			html.append("var uid = this.id.substring(12);").append("\r\n");
			html.append("doQueryChannelAction(uid); ").append("\r\n");
			html.append("});").append("\r\n");
			html.append("});").append("\r\n");
			html.append("//-->").append("\r\n");
			html.append("</script>").append("\r\n");
			html.append("");	
		}else
		{
			html.append("<tr>").append("\r\n");
			html.append("<td colspan=\"8\" align=\"center\">")
			.append("無超商資料")
			.append("</td>").append("\r\n");
			html.append("</tr>").append("\r\n");
		}


		return html.toString();
	}

	/*TODO  jeff 新的的取得xls */
	@Override
	public String doExportGroupStatisticsXls(Group group, String[] channels,
			Date[] dateFroms, Date[] dateTos) {

		if(null==group)
			group=new Group();

		if (!UserUtil.isBankGroup())
		{
			group=UserUtil.getUserGroup();
		}

		Workbook wb = new HSSFWorkbook(); // 若要產生xlsx則使用 XSSFWorkbook 即可
		Map<String, CellStyle> styles = createStyles(wb);

		Sheet sheet = wb.createSheet("超商傳輸統計表");
		PrintSetup printSetup = sheet.getPrintSetup();
		printSetup.setLandscape(true);
		sheet.setFitToPage(true);
		sheet.setHorizontallyCenter(true);
		sheet.setZoom(3, 4);
		sheet.setColumnWidth(0, 256*25);
		sheet.setColumnWidth(1, 256*10);
		sheet.setColumnWidth(3, 256*20);
		sheet.setColumnWidth(4, 256*20);
		sheet.setColumnWidth(5, 256*20);
		sheet.setColumnWidth(6, 256*20);


		// 行數
		int rownum = 0;

		//title row
		Row titleRow = sheet.createRow(rownum++);
		titleRow.setHeightInPoints((float)32.25);
		Cell titleCell = titleRow.createCell(0);
		titleCell.setCellValue("超商／郵局傳輸統計表");
		titleCell.setCellStyle(styles.get("title"));
		sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$G$1"));

		Row blankRow = sheet.createRow(rownum++);
		blankRow.setHeightInPoints((float)18);

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");

		for(int i=0;i<channels.length;i++)
		{
			String channel = channels[i];
			Date dateFrom = dateFroms[i];
			Date dateTo = dateTos[i];
			if(channel != null && !"".equals(channel))
			{
				Row dataRow = sheet.createRow(rownum++);
				Cell dataCell;
				dataCell = dataRow.createCell(0);
				dataCell.setCellValue(codeTableDao.getCodeTable("CHANEL", channel).getCodeName() + "：" + dateFormat.format(dateFrom)+"～" + dateFormat.format(dateTo));
				dataCell.setCellStyle(styles.get("title2"));
				sheet.addMergedRegion(CellRangeAddress.valueOf("$A$"+rownum+":$G$" + rownum));
			}

		}


		//串欄位表頭
		String[] titles = {
				"傳輸日期","超商","CODE" ,"代收筆數", "代收金額" , "代收手續費", "實撥金額"};

		Row headerRow = sheet.createRow(rownum++);
		headerRow.setHeightInPoints((float) 25.5);
		Cell headerCell;



		for (int i = 0; i < titles.length; i++) {
			headerCell = headerRow.createCell(i);
			headerCell.setCellValue(titles[i]);
			headerCell.setCellStyle(styles.get("header"));
		}

		//總計數據
		Long totalCount = new Long(0);
		Long totalAmount = new Long(0);
		Long totalFee = new Long(0);
		Long totalRealAmount = new Long(0);

		//      Long mainCount = new Long(0);
		//    	Long mainTotalAmount = new Long(0);
		//    	Long mainRealAmount = new Long(0);
		String cellRangeAddress = null;

		for(int i=0;i<channels.length;i++)
		{
			String channel = channels[i];
			Date dateFrom = dateFroms[i];
			Date dateTo = dateTos[i];
			int start = 0;

			//個別超商統計值
			Long channelCount = new Long(0);
			Long channelAmount = new Long(0);
			Long channelFee = new Long(0);
			Long channelRealAmount = new Long(0);

			List<String> commissionCodes = this.queryGroupCommissionCodes(group, channel, dateFrom, dateTo);
			if(commissionCodes == null)
			{
				if(channel != null && !"".equals(channel))
				{
					Row dataRow = sheet.createRow(rownum++);
					Cell dataCell;
					dataCell = dataRow.createCell(0);
					dataCell.setCellValue(dateFormat.format(dateFrom)+"～" + dateFormat.format(dateTo));
					dataCell.setCellStyle(styles.get("cell"));
					dataCell = dataRow.createCell(1);
					dataCell.setCellValue(codeTableDao.getCodeTable("CHANEL", channel).getCodeName());
					dataCell.setCellStyle(styles.get("cell"));
					dataCell = dataRow.createCell(2);
					dataCell.setCellValue("查無資料 ");
					dataCell.setCellStyle(styles.get("cell"));
					sheet.addMergedRegion(CellRangeAddress.valueOf("$C$"+rownum+":$G$" + rownum));
				}
			}else
			{
				start = rownum + 1;
				for(String code:commissionCodes)
				{

					// 取得超商(不含郵局)符合Code手續費
					long fee =0L;
					if (!channel.equals("H")) //非郵局
					{	
						CommissionCodeTable commissionCodeTable = commissionCodeTableDao.getCommissionCodeTable(code);
						if (commissionCodeTable!=null)       	            
							fee = commissionCodeTable.getGroupAmount();
					}

					//取得符合channel與commissionCode的每筆Feedback Log資料,組成統計值
					List<Map<String, Object>> fbLogs = this.queryGroupFeedbackLog(group,channel, code, dateFrom, dateTo);

					//個別Code統計值
					Long codeCount = new Long(0);
					Long codeAmount = new Long(0);
					Long codeFee = new Long(0);
					Long codeRealAmount = new Long(0);

					for(Map<String, Object>fblog:fbLogs)
					{
						codeCount++;
						long txamt = ((BigDecimal)fblog.get("txamt")).longValue();  
						codeAmount += txamt;
						//取得郵局手續費
						if (channel.equals("H")) //郵局
						{
							Group gp = getGroupByVirtualAccount((String)fblog.get("userno"));
							if (gp == null)
								fee = 0;
							else
							{	
								groupDao.findByPk((long)1);
								if (txamt<=100) fee = gp.getPostLevel1();
								else if (txamt<=1000) fee = gp.getPostLevel2();
								else if (txamt>1000) fee = gp.getPostLevel3();
							}	
						}
						codeFee += fee;
						codeRealAmount += txamt - fee;
					}

					if(fbLogs != null && fbLogs.size() >0)
					{
						int commissionStart = rownum + 1;

						Row dataRow = sheet.createRow(rownum++);
						Cell dataCell;
						dataCell = dataRow.createCell(0);
						dataCell.setCellValue(dateFormat.format(dateFrom)+"～" + dateFormat.format(dateTo));
						dataCell.setCellStyle(styles.get("cell"));
						dataCell = dataRow.createCell(1);
						dataCell.setCellValue(codeTableDao.getCodeTable("CHANEL", channel).getCodeName());
						dataCell.setCellStyle(styles.get("cell"));
						dataCell = dataRow.createCell(2);
						dataCell.setCellValue(code);
						dataCell.setCellStyle(styles.get("cell"));
						dataCell = dataRow.createCell(3);
						dataCell.setCellValue(codeCount);
						dataCell.setCellStyle(styles.get("cell_ALIGN_RIGHT"));
						dataCell = dataRow.createCell(4);
						dataCell.setCellValue(codeAmount);
						dataCell.setCellStyle(styles.get("cell_number"));
						dataCell = dataRow.createCell(5);
						dataCell.setCellValue(codeFee);
						dataCell.setCellStyle(styles.get("cell_number"));
						dataCell = dataRow.createCell(6);
						dataCell.setCellValue(codeRealAmount);
						dataCell.setCellStyle(styles.get("cell_number"));

						sheet.addMergedRegion(CellRangeAddress.valueOf("$C$"+commissionStart+":$C$" + rownum));
					}	

					//加統計值
					channelCount += codeCount;
					channelAmount += codeAmount;
					channelFee += codeFee;
					channelRealAmount += codeRealAmount;

				}

				Row dataRow = sheet.createRow(rownum++);
				Cell dataCell;
				dataCell = dataRow.createCell(0);
				dataCell.setCellValue(dateFormat.format(dateFrom)+"～" + dateFormat.format(dateTo));
				dataCell.setCellStyle(styles.get("cell"));
				dataCell = dataRow.createCell(1);
				dataCell.setCellValue(codeTableDao.getCodeTable("CHANEL", channel).getCodeName());
				dataCell.setCellStyle(styles.get("cell"));

				dataCell = dataRow.createCell(2);				
				dataCell.setCellValue("統計");
				dataCell.setCellStyle(styles.get("cell"));
				//sheet.addMergedRegion(CellRangeAddress.valueOf("$C$"+rownum+":$D$" + rownum));

				/* 效能提升  超商／郵局傳輸統計查詢  總計記數 */
				dataCell = dataRow.createCell(3);
				dataCell.setCellValue(channelCount);
				dataCell.setCellStyle(styles.get("cell_ALIGN_RIGHT"));

				dataCell = dataRow.createCell(4);				
				dataCell.setCellValue(channelAmount);

				dataCell.setCellStyle(styles.get("cell_number"));
				dataCell = dataRow.createCell(5);
				dataCell.setCellValue(channelFee);
				dataCell.setCellStyle(styles.get("cell_number"));
				dataCell = dataRow.createCell(6);
				dataCell.setCellValue(channelRealAmount);
				dataCell.setCellStyle(styles.get("cell_number"));


				//總合計
				totalCount += channelCount;
				totalAmount += channelAmount;
				totalFee += channelFee;
				totalRealAmount += channelRealAmount;

				sheet.addMergedRegion(CellRangeAddress.valueOf("$A$"+start+":$A$" + rownum));
				sheet.addMergedRegion(CellRangeAddress.valueOf("$B$"+start+":$B$" + rownum));
			}

		}

		Row dataRow = sheet.createRow(rownum++);
		Cell dataCell;
		sheet.addMergedRegion(CellRangeAddress.valueOf("$A$"+rownum+":$B$" + rownum));
		dataCell = dataRow.createCell(0);
		dataCell.setCellValue("總計");
		dataCell.setCellStyle(styles.get("cell"));
		dataCell = dataRow.createCell(1);				
		dataCell.setCellStyle(styles.get("cell"));

		//sheet.addMergedRegion(CellRangeAddress.valueOf("$C$"+rownum+":$D$" + rownum));

		dataCell = dataRow.createCell(2);				
		dataCell.setCellValue("超商／郵局合計");
		dataCell.setCellStyle(styles.get("cell"));
		/* 效能提升  超商／郵局傳輸統計查詢  總計記數 */
		dataCell = dataRow.createCell(3);
		dataCell.setCellValue(totalCount);
		dataCell.setCellStyle(styles.get("cell_ALIGN_RIGHT"));
		dataCell = dataRow.createCell(4);
		dataCell.setCellValue(totalAmount);
		dataCell.setCellStyle(styles.get("cell_number"));
		dataCell = dataRow.createCell(5);
		dataCell.setCellValue(totalFee);
		dataCell.setCellStyle(styles.get("cell_number"));
		dataCell = dataRow.createCell(6);
		dataCell.setCellValue(totalRealAmount);
		dataCell.setCellStyle(styles.get("cell_number"));



		int colCount = 0;
		/* 效能提升  超商／郵局傳輸統計查詢  總計記數 */
		while (colCount <= titles.length) {
			sheet.autoSizeColumn((short) colCount++,true);//自動調整欄寬
		}

		String tempDownloadFilePath = tempDirectory + "/" + UserUtil.getUserGroup().getGroupNo() + "/" + UserUtil.getUserId() + "/";
		File directory = new File(tempDownloadFilePath);             
		if(!directory.exists())
		{
			try {
				FileUtils.forceMkdir(directory);
			}
			catch (IOException e) {
				logger.error("{}",e);
			}
		}

		String fileFullName = tempDownloadFilePath + UUID.randomUUID().toString() + "-超商傳輸統計表.xls"; //

		FileOutputStream out;
		try {
			out = new FileOutputStream(fileFullName);
			wb.write(out);
			out.close();
		}
		catch (FileNotFoundException e) {
			logger.error("{}",e);
		}
		catch (IOException e) {
			logger.error("{}",e);
		}
		return fileFullName;
	}

	/*TODO 20120925 0447 jeff 新的的取得FeedbackLog (總計明細) */
	public PaginatedList<Map<String, Object>> queryGroupFeedbackLogByChannel(Group group, String channels[],
			Date dateFroms[], Date dateTos[],PaginatedList<Map<String, Object>> paginationConfig) {
		/*
		 *	畫面上的總計放大鏡
		 *	應該要傳所查詢的通路跟各通路的時間
		 */
		Map<String, String> channelCode=new HashMap<String, String>();

		channelCode.put( "7111111","D");
		channelCode.put("TFM","E" );
		channelCode.put( "HILIFE","F");
		channelCode.put( "OKCVS","G");
		channelCode.put("POST","H");



		if(null==group)
			group=new Group();

		if (!UserUtil.isBankGroup())
		{
			group=UserUtil.getUserGroup();
		}

		PaginatedList<Map<String, Object>> fbLogs = soez5008Dao.queryTotalGroupFeedbackLog(group, channels, dateFroms, dateTos, paginationConfig);

		if(fbLogs.getPaginatedList()== null || fbLogs.getPaginatedList().size() == 0)
			return null;

		// 取得超商(不含郵局)符合Code手續費
		long fee =0L;



		/* 效能提升  超商／郵局傳輸統計查詢  總計記數 */
		Long totalCount = new Long(0);
		Long totalAmount = new Long(0);
		Long totalFee = new Long(0);

		/* 設定複製用PaginatedList 再對資料作處理 不然 foreach的狀況下不能對來源檔案作操作  */
		PaginatedList<Map<String, Object>> results = new PaginatedList<Map<String, Object>>();				
		results.setFullListSize(fbLogs.getFullListSize());
		results.setPageSize(fbLogs.getPageSize());
        results.setPageNumber(fbLogs.getPageNumber());
        results.setSortCriterion(fbLogs.getSortCriterion());
        results.setSortDirection(fbLogs.getSortDirection());
   
		List<Map<String, Object>> temp = new ArrayList<Map<String, Object>>();
		for(Map<String, Object> fblog:fbLogs.getPaginatedList())
		{	
			//個別Code統計值
			Long codeCount = new Long(0);
			Long codeAmount = new Long(0);
			Long codeFee = new Long(0);
			String channel = (String)fblog.get("channel");
			String code = (String)fblog.get("code");
			if (!channel.equals("H")) //非郵局
			{	
				CommissionCodeTable commissionCodeTable = commissionCodeTableDao.getCommissionCodeTable(code);
				if (commissionCodeTable!=null)       	            
					fee = commissionCodeTable.getGroupAmount();
			}

			/*超商欄位*/
			String  codeName =  codeTableDao.getCodeTable("CHANEL", channelCode.get(channel)).getCodeName();
			fblog.put("codeName", codeName);
			/*代號*/
			fblog.put("commissionCode", code);

			String userno = (String)fblog.get("userno");

			//取得郵局繳費日期
			if (channel.equals("H")) //郵局
			{
				Payment payment = paymentDao.queryPaymentByVirtualAccount(userno,true);
				if (payment==null) payment = paymentDao.queryPaymentByVirtualAccount(userno,false);
				if (payment!=null) fblog.put("dueday", payment.getPayDue()); 
			}		

			//取得帳單業者
			String gname = (String)fblog.get("gname");

			if (gname == null)
				fblog.put("gpname", "");
			else
			{
				fblog.put("gpname", gname);
			}

			//計算手續費
			long txamt = ((BigDecimal)fblog.get("txamt")).longValue();
			if (channel.equals("H")) //郵局
			{
				long post1 = ((BigDecimal)fblog.get("post1")).longValue();
				long post2 = ((BigDecimal)fblog.get("post2")).longValue();
				long post3 = ((BigDecimal)fblog.get("post3")).longValue();
			
				if (txamt<=100) fee = post1;
				else if (txamt<=1000) fee =post2;
				else if (txamt>1000) fee = post3;
			}
			fblog.put("fee", fee);
			//個別Code統計值
			//codeCount++;
			//codeAmount += txamt;
			//codeFee +=fee;
			//加統計值
			//totalCount += codeCount;
			//totalAmount += codeAmount;
			//totalFee += codeFee;
			if(fbLogs.isLastPage()){	
				Map<String, Object> total=fbLogs.getTotalObject();
				fblog.put("totalCount", total.get("totalCount"));
				fblog.put("totalAmount", ((BigDecimal)total.get("totalAmount")).longValue());
				fblog.put("totalFee", ((BigDecimal)total.get("totalFee")).longValue());
			}
			/*計算總計*/
			temp.add(fblog);

		}

		results.setPaginatedList(temp);
		/* 清除資源*/
		fbLogs.getPaginatedList().clear();
		fbLogs=null;

		return results;
	}
}
